<template>
  <div class="userInput">
    <div class="userFunction">
      <!-- zk新增，faceshow为true，禁用提示 -->
      <Tooltip content="表情" placement="bottom" :disabled="faceShow">
        <div @click.stop.prevent="setFaceShow" class="face_box" id="face_box">
          <i class="face_parent" v-show="faceShow" @click.stop.prevent="" @blur="faceShow = false">
            <i v-for="(item, index) in expression" class="face_parent_child" v-show="faceChoose == index"
              :key="`ex_${index}`">
              <el-tooltip v-for="(temp, count) in item" :key="'face' + count" :content=temp placement="bottom"
                effect="light" transition='false'>
                <img draggable="false" :src="`static/image/face/${index * 36 + count}.gif`" style="margin: 0.3em"
                  @click="chooseFaceIndex(index, count)" />
              </el-tooltip>
            </i>
            <p class="face_choose_parent">
              <i class="face_choose_ibtn" v-for="(v, k) in 3" :class="{ face_check_bg: faceChoose == k }"
                @click.stop.prevent="setFaceChoose(k)" :key="`exa_${v}`"></i>
            </p>
          </i>
        </div>
      </Tooltip>
      <Tooltip content="截图" placement="bottom" id="screenshot">
        <div @click.stop.prevent="getMap" class="screenshot"></div>
        <i class="screenshotType" @click="isScreenCheck = !isScreenCheck"></i>
        <div class="screenCheck" v-show="isScreenCheck" @click="screenshotChange()">
          <img :src="screenType
            ? require(`../../../static/image/home/chat/screenshots_yet.png`)
            : require(`../../../static/image/home/chat/screenshots_not.png`)
            " />截图时隐藏当前窗口
        </div>
      </Tooltip>
      <Tooltip content="发送文件" placement="bottom">
        <div id="file_test" @click="OpenFileDialog(0)">
        </div>
      </Tooltip>
      <Tooltip content="发送图片" placement="bottom">
        <div class="sendimg" @click="OpenFileDialog(1)">
        </div>
      </Tooltip>
      <h6 v-show="specified_show && group_people_show.length > 0" class="specified_parent"
        :style="{ left: CoordsX + 'px', bottom: CoordsY + 'px' }">
        <p v-for="(item, index) in group_people_show" v-html="item" :key="'pepole' + index" class="specified_detail"
          @click.stop.prevent="toSpecified(item)">
        </p>
      </h6>
      <Tooltip content="免打扰" placement="bottom" :disabled="tipFlag" v-show="toInfo.id != 'fileAssistant'">
        <div class="disturb" :class="{ active: messageFree }" @click="updateMessageFree"></div>
      </Tooltip>
      <!-- 提示文字显隐控制 -->

      <Tooltip content="快捷回复" placement="bottom" v-show="toInfo.isGroup == '0' && toInfo.id != 'fileAssistant'"
        :disabled="quickShow">
        <div class="quick_response m-no-select" @click.stop.prevent="quickClick" :class="{ active: quickShow }">
          <div class="quick_wrap" v-show="quickShow">
            <ul>
              <li v-for="(item, index) in quickList" :key="'quick' + index"
                @click.stop.prevent="quickReply(item.content)">
                {{ item.content }}
              </li>
            </ul>
          </div>
        </div>
      </Tooltip>
      <Tooltip content="设置字体" placement="bottom" style="margin-right: 0px" :disabled="setSizeShow">
        <div class="set_font" @click.stop.prevent="setSizeShow = !setSizeShow" :class="{ active: setSizeShow }"></div>
      </Tooltip>
      <span class="stfz_wrap" v-show="setSizeShow" style="margin-left: 10px">
        <el-color-picker v-model="colorValue" size="mini"></el-color-picker>
        <i-select class="sizePick" v-model="sizeValue" size="small" style="width: 80px" :placeholder="sizeValue + ''">
          <i-option v-for="(item, index) in fontSizeList" :value="item.size" :key="'font' + index">{{ item.size }}
          </i-option>
        </i-select>
        <b :class="{ isBold: boldValue == 'bold', isNormal: boldValue == 'normal' }" @click="setBold">加粗
        </b>
      </span>
      <Tooltip placement="bottom" content="远程桌面" style="margin-left: 20px"
        v-show="toInfo.isGroup == '0' && toInfo.id != 'fileAssistant'" :disabled="control_show">
        <div class="conterol_icon" :class="{ active: control_show }" @click.stop.prevent="controlActive">
          <div class="control_t_wrap" v-show="control_show">
            <ul>
              <!-- <li @click.stop.prevent='controlFn(9)'>邀请同屏</li> -->
              <li @click.stop.prevent="controlFn(1)">控制对方电脑</li>
              <li @click.stop.prevent="controlFn(2)">请求远程协助</li>
            </ul>
          </div>
        </div>
      </Tooltip>
      <!-- 修改群语录权限，myposition!="3"=>toInfo.isGroup=="1" -->
      <Tooltip placement="bottom" content="重点语录" style="margin: 0 0 0 20px" v-show="toInfo.isGroup == '1'">
        <div class="quotation_icon" @click.stop.prevent="toGroupFunction(3, true)"></div>
      </Tooltip>
      <Tooltip placement="bottom" content="群公告" style="margin-left: 20px" v-show="toInfo.isGroup == '1'">
        <div class="announcement_icon" @click.stop.prevent="groupNoticeClick"></div>
      </Tooltip>
      <Tooltip content="聊天记录" placement="bottom-end" style="margin-right: 0; position: absolute; right: 20px">
        <div id="records_btn">
          <div style="background-size: cover" @click.stop.prevent="toGroupFunction(1, true)"
            :class="{ activeRecords: activeRecords }"></div>
        </div>
      </Tooltip>
    </div>
    <div class="userMainInput" tabindex="-1" name="contentInput" contenteditable="true" ref="contentInput"
      @focus="content_input_focus" id="contentInput" @keyup="keyArr" @blur="contentBlur" @click="editEleClick"
      @paste="pasteEvent($event)" @contextmenu="copyRignt($event)" v-viewer="{ download: false }" :style="{
        fontSize: sizeValue + 'px',
        color: colorValue,
        fontWeight: boldValue,
      }"></div>
    <div class="replayWrap" v-show="isReplay">
      <div id="replay" ref="replay"></div>
      <img src="static\image\home\clear_icon.png" alt="" @click="delReplay" />
    </div>
    <div class="userMainFoot" v-if="senHot == 1">
      <div class="send_tip">Enter发送，Ctrl+Enter换行</div>
      <Button class="send_btn" type="success" @click.native="sendMsg('text')">发 送</Button>
    </div>
    <div class="userMainFoot" v-else>
      <div class="send_tip">Ctrl+Enter发送，Enter换行</div>
      <Button class="send_btn" type="success" @click.native="sendMsg('text')">发 送</Button>
    </div>
    <div class="copy_paste_btn" v-if="copyShow" :style="{ top: pasteMenuTop + 'px', left: pasteMenuLeft + 'px' }">
      <span @mousedown="copyValue($event)">复制</span>
      <span @mousedown="copyMain($event)">粘贴</span>
    </div>
    <div class="file_tp_wrap">
      <div ref="imageTofile" class="file_tp_view">
        <img ref="imageFileSrc" :src="fileSuffix
          ? types[fileSuffix]
            ? require(`../../../static/image/home/type_${fileSuffix}.png`)
            : require(`../../../static/image/home/file_icon.png`)
          : require(`../../../static/image/home/file_icon.png`)
          " />
        <div ref="imageFileName">{{ fileName }}</div>
      </div>
    </div>
    <canvas id="test" width="200" height="42" style="display: none"></canvas>
  </div>
</template>

<script>
import { getProgress_axios, setUserDnd } from "@/api/newsEditor";
import { mapState } from "vuex";
import { resolve } from "url";
export default {
  components: {},
  props: {
    senHot: {
      type: String,
      default: 0,
    },
    isOndropHandle: {
      //文件是否处理中
      type: Boolean,
      default: false,
    },
    copyShow: {
      type: Boolean,
      default: false,
    },
    control_show: {
      type: Boolean,
      default: false,
    },
    quickShow: {
      type: Boolean,
      default: false,
    },
    specified_show: {
      type: Boolean,
      default: false,
    },
    toInfo: {
      type: Object,
      default: () => {
        return {
          id: "",
          name: "",
          isGroup: false,
        };
      },
    },
    faceShow: {
      // type: Object,
      type: Boolean, //zk修改faceshow的数据类型为布尔值
      default: false,
    },
    personalStatus: {
      type: Number,
      default: 0,
    },
    group_detail: {
      type: Object,
      default: () => {
        return {
          users: [],
        };
      },
    },
    messageFree: {
      type: Boolean,
      default: false,
    },
    chatList: {
      type: Array,
      default: [[], []],
    },
    sessionList: {
      type: Array,
      default: [],
    },
    activeRecords: {
      type: Boolean,
      default: false,
    },
    contentReset: {
      type: Number,
      default: 0,
    },
    free_list: {
      type: Array,
      default: () => {
        return [];
      },
    },
    expression: {
      type: Array,
      default: () => {
        return {};
      },
    },
    isDissolve: {
      type: Boolean,
      default: false,
    },
    clipBoardFile: {
      type: Object,
      default: () => {
        return {};
      },
    },
    siderArray: {
      type: Array,
      default: () => {
        return [
          {
            title: "会话",
            url: "static/image/home/btn_news_nor.png",
            src: "static/image/home/btn_news_sel.png",
            active: true,
          },
          {
            title: "通讯录",
            url: "static/image/home/btn_contact_nor.png",
            src: "static/image/home/btn_contact_sel.png",
            active: false,
          },
        ]; //侧边栏列表
      },
    },
    // isScreenshot: {
    //   type: Boolean,
    //   default: false,
    // },
    isScreenshot: {
      type: Object,
      default: () => {
        return {}
      },
    },
    pageFlagShow: {
      type: Boolean,
      default: false,
    },
    currentTempChat: {
      //zk新增，暂存10条
      type: Array,
      default: () => {
        return [[], []];
      },
    },
  },
  data() {
    return {
      sendGap: null, //发送间隔
      isReplay: false,
      isScreenCheck: false,
      screenType: false, //截图是否隐藏窗体
      group_people: [],
      group_people_show: [],
      group_people_gap: null,
      maxMessagrLength: 500, //zk新增，消息最大长度
      setKeySend: 0,
      pasteMenuLeft: 0,
      pasteMenuTop: 0,
      lastEditRange: null, //光标最后位置
      types: {
        folder: true,
        pdf: true,
        exe: true,
        excel: true,
        html: true,
        img: true,
        ppt: true,
        tmp: true,
        txt: true,
        video: true,
        voice: true,
        word: true,
        rar: true,
        zip: true,
      },
      fileSuffix: "",
      fileList: [],
      fileName: "",
      faceChoose: 0,
      userValue: "",
      setSizeShow: false,
      sizeValue: 14, //字体大小
      colorValue: "#000", //字体颜色
      boldValue: "normal", //字体粗细
      fontStyle: "", //字体样式,兼容旧版(库只存字体大小)
      fontSizeList: [
        {
          size: 12,
        },
        {
          size: 14,
        },
        {
          size: 16,
        },
        {
          size: 18,
        },
        {
          size: 20,
        },
        {
          size: 22,
        },
        {
          size: 24,
        },
        {
          size: 26,
        },
      ], //字体列表
      // userInputKey: new Date().getTime(),
      quickList: [
        {
          content: "好的,稍后回复。",
        },
        {
          content: "收到,正在查看。",
        },
        {
          content: "会议中,不方便回复。",
        },
      ],
      // lastEditRange: 0,
      contentClear: false,
      // copyShow: false,
      isPasteDrop: false,
      fielIsRepeatList: [], // 新增判断复制粘贴文件是否为同一个内容
      tipFlag: false, //免打扰按钮提示禁用
      picCopyList: [],
      contentFocus: false, //是否正在编辑
      sendReply: "", //待发送的回复
      showAt: true, //@显示
      CoordsX: 0,
      CoordsY: 0,
    };
  },
  watch: {
    pageFlagShow(newValue) {
      if (newValue) {
        this.$refs.contentInput.focus();
      }
    },
    toInfo: {
      handler(newValue, oldValue) {
        this.delReplay();
      },
      deep: true,
      immediate: true,
    },
    senHot: {
      handler(newValue, oldValue) {
        this.$forceUpdate();
      },
      deep: true,
      immediate: true,
    },
    user_hot_key: {
      handler(newValue, oldValue) {
        this.$forceUpdate();
      },
      deep: true,
      immediate: true,
    },
    contentReset() {
      // console.log(this.contentReset,'输入框重置');
      this.userValue = this.$refs.contentInput.innerHTML = "";
      this.lastEditRange = 0;
      if (this.$store.state.chatInputContent[this.toInfo.id]) {
        this.insertContent(this.$store.state.chatInputContent[this.toInfo.id]);
        // this.userValue = this.$refs.contentInput.innerHTML = this.$store.state.chatInputContent[this.toInfo.id];
      }
    },
    isScreenshot(newval, oldval) {
      //zk15新增，newval和oldval
      console.log(newval, oldval)
      if (newval.return_code == "TRUE") {
        //读取剪贴板
        let infs = this.$shell("GetClipboardData", []);
        infs = eval("(" + infs + ")");
        console.log(infs, 400);
        if (infs.return_code === "TRUE") {
          if (newval.return_msg == '已截图') {
            if (infs.return_data.formats == "Bitmap") {
              this.insertContent(
                `<img draggable="false" suffix='png' src='${infs.return_data.data}' type="img" style='max-width:8em;max-height:6em;'>`
              );
            }
          }
          if (newval.return_msg == '截图分享') {
            //调用外壳处理图像
            let resImg = infs.return_data.data.split(",")[1]
            let res = this.$shell("SaveFileStream", [
              this.myInfo.id,
              resImg,
              'png',
            ]);
            res=JSON.parse(res)
            console.log(res, 434);
            //上传图像
            let data = this.$utilJs.dataURItoBlob(infs.return_data.data)
            let form = this.get_2_data(data);
            this.$upload(
              "api/v1/oim/image/upload.do",
              form,
              (info) => {
                console.log(
                  info.data.id, 443)
                let item = {
                  value: res.return_msg,
                  type: "image",
                  DownLoadId: info.data.id,
                  duration: 32,
                  smallValue: res.return_msg
                }
                this.$emit("toForwarding", item);
              }
            )

            console.log('我要转发')
          }
        }
      }
    },
    toReply(newval, oldval) {
      if (!newval) {
        return;
      }
      this.isReplay = true;
      if (newval.type == "text") {
        let isTrue = this.toInfo.isGroup == "1";
        let str;
        str = `${isTrue ? this.sqlTable.messageList : this.sqlTable.privateList
          } WHERE messageId='${newval.messageId}'`;
        let res = this.operationalDatabase(
          `SELECT * FROM  ${str} ORDER BY time DESC;`,
          1
        );
        if (res.list.length > 0) {
          newval.value = res.list[0].value;
        }
      }
      let htmlValue = `${newval.name ? newval.name : ""}：${newval.type == "image"
        ? "[图片]"
        : newval.type == "audio"
          ? "[音频]"
          : newval.type == "GPS"
            ? eval("(" + JSON.parse(newval.value) + ")").address || "[GPS]"
            : newval.value
        }`;
      this.sendReply = htmlValue;
      if (htmlValue.length > 50) {
        htmlValue = htmlValue.substring(0, 50) + "...";
      }
      this.$refs.replay.innerHTML = htmlValue;
      this.insertHtmlAtCaret();
      this.$refs.replay.innerHTML = this.$refs.replay.innerHTML.replace(
        /\s$/,
        ""
      );
      // this.$set(item, 'functionShow', false);// 导致回复触发2次
      this.$store.commit("setToReply", null);
    },
    clipBoardFile() {
      let _this = this;
      this.$nextTick(() => {
        setTimeout(() => {
          _this.handleClipBoardFile(_this.cloneObject(_this.clipBoardFile));
        }, 100);
      });
    },
    colorValue() {
      this.fontStyle = JSON.stringify({
        //保存字体样式
        size: this.sizeValue,
        color: this.colorValue,
        bold: this.boldValue,
      });
      var rep = this.operationalDatabase(
        `UPDATE system_${this.myInfo.id} SET setFont='${this.fontStyle}' WHERE id='${this.myInfo.id}';`
      );
    },
    sizeValue() {
      this.fontStyle = JSON.stringify({
        //保存字体样式
        size: this.sizeValue,
        color: this.colorValue,
        bold: this.boldValue,
      });
      var rep = this.operationalDatabase(
        `UPDATE system_${this.myInfo.id} SET setFont='${this.fontStyle}' WHERE id='${this.myInfo.id}';`
      );
    },
    boldValue() {
      this.fontStyle = JSON.stringify({
        //保存字体样式
        size: this.sizeValue,
        color: this.colorValue,
        bold: this.boldValue,
      });
      var rep = this.operationalDatabase(
        `UPDATE system_${this.myInfo.id} SET setFont='${this.fontStyle}' WHERE id='${this.myInfo.id}';`
      );
    },
    // picCopyList(newval, olval){
    //   if(newval.length != olval.length){
    //     alert("值变了")
    //     let arr = [];
    //     newval.forEach(i => arr.push(i.currentSrc))
    //     console.log(JSON.stringify(arr))
    //     // this.$shell("PicCopy", newval);
    //   }
    // }
    '$store.state.chatChooseFileWait': {
      handler: function(newval, oldval){
        console.log('壳',newval)
        if(newval && newval.type==='done' && newval.toInfoId===this.toInfo.id && newval.myInfoId===this.myInfo.id){
          let newWaitArr = (newval.waitArr||[]).filter((it)=>{
            return !!it.fileId;
          });
          if(newWaitArr.length === (newval.waitArr||[]).length){
            newWaitArr.forEach((item)=>{
              console.log(1183,'壳',item)
              let sendValueImg = Object.assign(
                {
                  uploading: false,
                },
                {
                  upload: 0,
                },
                this.generateMsg_imgFile(
                  "image",
                  item.fileInfo.FileName,
                  item.messageId,
                  item.fileInfo.FileSize,
                  1,
                  item.fileId,
                  item.fileInfo.FilePath
                )
              )
              console.log(1182,'壳',sendValueImg)
              this.$emit("backBottom");
              this.$emit("updateChatList", sendValueImg);
              setTimeout(()=>{
                this.$emit('chatScrollToBottom');
              },100)
            })
            this.$Message.success("发送成功");
            //this.$showMsg('发送成功','success')
            this.$store.commit('setChatChooseFileWait',null)
          }
        }
      },
      deep: true,
    },
  },
  filters: {
    setGroupUser(str) {
      return str.length > 4 ? str.slice(0, 4) + "..." : str;
    },
  },
  computed: {
    ...mapState(["myInfo", "user_hot_key", "ws", "isService"]),
    tableId() {
      return this.myInfo.id;
    },
    sqlTable() {
      return {
        userHotKey: `user_hot_key`,
        uninterruptedList: `uninterrupted_list_${this.tableId}`, //免打扰列表
        userInformation: `user_information_${this.tableId}`, //用户信息表
        sessionList: `session_list_${this.tableId}`, //会话列表
        broadcastList: `broadcast_list_${this.tableId}`, //广播列表
        publicList: `public_list_${this.tableId}`, //公众号列表
        groupList: `group_list_${this.tableId}`, //群列表
        messageList: `message_list_${this.tableId}`, //群聊消息表
        privateList: `private_list_${this.tableId}`, //单聊消息表
        publicRecords: `public_records_${this.tableId}`, //公众号记录表
        groupUsers: `group_users_${this.tableId}`, //	groupMessageEnity: 'GroupMessageEnity_' + this.myInfo.id,
        systemTable: `system_${this.tableId}`,
      };
    },
    toReply() {
      return this.$store.state.toReply;
    },
  },
  methods: {
    //删除回复
    delReplay() {
      if (this.$refs.replay) {
        this.isReplay = false;
        this.sendReply = "";
        this.$refs.replay.innerHTML = "";
      }
    },
    setBold() {
      if (this.boldValue == "normal") {
        this.boldValue = "bold";
      } else this.boldValue = "normal";
    },
    //记录截屏选项
    screenshotChange() {
      this.screenType = !this.screenType;
      this.isScreenCheck = false;
      this.$store.commit("setScreenshotFilter", this.screenType);
      let a = this.screenType ? 1 : 0;
      let res = window.external.InvokeWinFormMethod(
        "Internal.Function",
        "GetMap",
        a,
        1
      );
    },
    setgunagbiao() {
      this.$refs.contentInput.focus();
      var selection = getSelection();
      console.log(selection, "selection");
      if (!selection) {
        return;
      }
      this.lastEditRange = selection.getRangeAt(0);
    },
    set_last_focus() {
      //设置最后光标
      this.$refs.contentInput.focus();
      var range = document.createRange();
      range.selectNodeContents(this.$refs.contentInput);
      range.collapse(false);
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
    },
    getPic(pic, text) {
      return new Promise((resolve, reject) => {
        let w = this.$refs.imageFileName.offsetWidth;
        //画布
        let canvas = document.getElementById("test");
        canvas.setAttribute("width", w + 60);
        // 画笔
        let ctx = canvas.getContext("2d");
        canvas.height = canvas.height;

        let img = new Image();
        img.src = pic;

        img.onload = function () {
          // 添加图像
          ctx.drawImage(this, 3, 2, 38, 38);

          // 添加文字
          ctx.font = "14px 微软雅黑 700 sans-serif";
          ctx.fillStyle = "#3c3b3b";
          ctx.fillText(text, 46, 15);
          resolve(canvas);
        };
      });
    },
    checkType(e) {
      if (e == "doc" || e == "docx") {
        return "word";
      } else if (e == "xls" || e == "xlsx") {
        return "excel";
      } else if (e == "ppt" || e == "pptx") {
        return "ppt";
      } else if (e == "png" || e == "jpg" || e == "jpeg" || e == "gif") {
        return "picture";
      } else if (
        e == "zip" ||
        e == "rar" ||
        e == "txt" ||
        e == "exe" ||
        e == "pdf" ||
        e == "html"
      ) {
        return e;
      } else {
        return "file";
      }
    },
    getDropChangeData(files) {
      //zk标识，拖拽文件生成的canvas
      // 新增粘贴/拖拽字段
      this.isPasteDrop = true;
      console.log(files, "拖拽文件数据返回");
      this.$refs.contentInput.focus();
      let _this = this;
      // 非聊天窗口拖拽过滤︿(￣︶￣)︿
      if (!this.siderArray[0].active) {
        return;
      }
      if (_this.updateDropState || _this.isInsertFile) {
        _this.$Message.warning("文件处理中,请稍后");
        return;
      }
      let pcFileList = [];
      try {
        pcFileList = JSON.parse(files) || [];
      } catch (err) {
        pcFileList = JSON.parse(files) || [];
      }
      //拦截超过500M的大文件
      this.$fileBigChoice(pcFileList);
      console.log(pcFileList, "pcFiles");
      // 判断是否为重复的粘贴文件
      this.fielIsRepeat(pcFileList, "FilePath");

      function insertFileItem(fileInfo, i) {
        return new Promise((resolve, reject) => {
          _this.isInsertFile = true;
          _this.$emit("updateDropState", true);
          try {
            // let suffix = fileInfo.FileName.toLowerCase().split(".").splice(-1);
            let suffix = fileInfo.FileName.toLowerCase().substring(
              fileInfo.FileName.toLowerCase().lastIndexOf(".") + 1
            );

            let initId = _this.$func.uuid();
            if (_this.$store.state.chatFileList[_this.toInfo.id]) {
              _this.$store.state.chatFileList[_this.toInfo.id].push({
                path: fileInfo.FilePath,
                uuid: initId,
                name: fileInfo.FileName,
                size: fileInfo.FileLength,
              });
            } else {
              _this.$store.state.chatFileList[_this.toInfo.id] = [];
              _this.$store.state.chatFileList[_this.toInfo.id].push({
                path: fileInfo.FilePath,
                uuid: initId,
                name: fileInfo.FileName,
                size: fileInfo.FileLength,
              });
            }
            if (fileInfo.FileName.length >= 15) {
              // _this.fileName = fileInfo.FileName.substring(0, 15) + '...' + suffix;
              _this.fileName =
                fileInfo.FileName.substring(
                  0,
                  fileInfo.FileName.lastIndexOf(".")
                ).substring(0, 15) +
                "..." +
                suffix;
            } else {
              _this.fileName = fileInfo.FileName;
            }

            _this.fileSuffix = _this.checkType(suffix);
            _this.$nextTick(() => {
              setTimeout(() => {
                //节点渲染完成后,canvas生成文件图片
                _this
                  .getPic(_this.$refs.imageFileSrc.src, _this.fileName)
                  .then((canvas) => {
                    console.log(canvas, 698);
                    let url = canvas.toDataURL();
                    document.execCommand(
                      "insertHTML",
                      false,
                      `<img type="_file" uuid="${initId}" src="${url}" _filepath="${fileInfo.FilePath}"/>`
                    );
                    // _this.insertContent(`<img type="_file" uuid="${initId}" src="${url}"/>`);
                    if (i == pcFileList.length - 1) {
                      _this.isInsertFile = false;
                      _this.$emit("updateDropState", false);
                    }
                    resolve();
                  })
                  .catch((err) => {
                    _this.isInsertFile = false;
                    _this.$emit("updateDropState", false);
                  });
              });
            });
          } catch (err) {
            _this.isInsertFile = false;
            _this.$emit("updateDropState", false);
          }
        });
      }
      async function insertFile() {
        for (let i = 0; i < pcFileList.length; i++) {
          console.log(pcFileList[i], "file");
          await insertFileItem(pcFileList[i], i);
        }
      }
      insertFile();
    },
    // 处理多文件拖拽到聊天框
    ondropHandle(fileInfo) {
      return new Promise((resolve, reject) => {
        let _this = this;
        try {
          let filesize = fileInfo.size / 1024 / 1024 || 0;
          if (filesize > 500) {
            this.$Message.warning(
              "您选择的文件包含过大文件,将被忽略(超过500M)"
            );
            resolve();
            return;
          }
          let initId = this.$func.uuid();
          var AllImgExt = ".jpg|.jpeg|.gif|.bmp|.png|.swf|.tiff";
          var extName = fileInfo.name
            .substring(fileInfo.name.lastIndexOf("."))
            .toLowerCase(); //（把路径中的所有字母全部转换为小写）
          if (AllImgExt.indexOf(extName + "|") == -1) {
            console.log(fileInfo.type, "type");
            let suffix = fileInfo.name.toLowerCase().split(".").splice(-1);
            let initId = this.$func.uuid();
            let fileReader = new FileReader();
            fileReader.onload = function (w) {
              let form = _this.get_2_data(fileInfo);
              // 文件数据存储,发送消息时匹配完清空
              if (_this.$store.state.chatFileList[_this.toInfo.id]) {
                _this.$store.state.chatFileList[_this.toInfo.id].push({
                  form: form,
                  uuid: initId,
                  name: fileInfo.name,
                  size: fileInfo.size,
                });
              } else {
                _this.$store.state.chatFileList[_this.toInfo.id] = [];
                _this.$store.state.chatFileList[_this.toInfo.id].push({
                  form: form,
                  uuid: initId,
                  name: fileInfo.name,
                  size: fileInfo.size,
                });
              }
              if (fileInfo.name.length >= 15) {
                _this.fileName =
                  fileInfo.name.substring(0, 15) + "..." + suffix;
              } else {
                _this.fileName = fileInfo.name;
              }
              _this.fileSuffix = _this.checkType(suffix);
              _this.$nextTick(() => {
                setTimeout(() => {
                  //节点渲染完成后,canvas生成文件图片
                  _this
                    .getPic(_this.$refs.imageFileSrc.src, _this.fileName)
                    .then((canvas) => {
                      let url = canvas.toDataURL();
                      document.execCommand(
                        "insertHTML",
                        false,
                        `<img type="_file" uuid="${initId}" src="${url}" />`
                      );
                      resolve();
                    });
                });
              });
            };
            fileReader.readAsDataURL(fileInfo);
            fileReader.addEventListener(
              "error",
              (e) => {
                _this.$Message.warning("您选择的文件包含无效文件,将被忽略");
                resolve();
              },
              false
            );
          } else {
            let fileReader = new FileReader();
            let suffix = fileInfo.name.toLowerCase().split(".").splice(-1);
            fileReader.onload = function (w) {
              document.execCommand(
                "insertHTML",
                false,
                `<img type="img" suffix="${suffix}" src="${w.target.result}" draggable="false" style="max-width:8em;max-height:6em;"/>`
              );
              resolve();
            };
            fileReader.readAsDataURL(fileInfo);
          }
        } catch (err) {
          reject(err);
        }
      });
    },
    //深克隆对象
    cloneObject(obj) {
      if (obj === null) return null;
      if (obj.constructor !== "object") return obj;
      if (obj.constructor === Date) return new Date(obj);
      if (obj.constructor === RegExp) return new RegExp(obj);
      var newObj = new obj.constructor(); //保持继承的原型
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          var val = obj[key];
          newObj[key] = typeof val === "object" ? arguments.callee(val) : val;
        }
      }
      return newObj;
    },
    // 处理粘贴板数据
    handleClipBoardFile(fileData = {}) {
      let _this = this;
      new Promise((resolve, reject) => {
        let suffix = fileData.name.toLowerCase().split(".").splice(-1);
        let initId = this.$func.uuid();
        let fileReader = new FileReader();
        let blobFile = this.$utilJs.dataURItoBlob(fileData.base64);
        let form = this.get_2_data(blobFile);
        // 文件数据存储,发送消息时匹配完清空
        if (this.$store.state.chatFileList[fileData.userid]) {
          this.$store.state.chatFileList[fileData.userid].push({
            form: form,
            uuid: initId,
            name: fileData.name,
            size: fileData.size,
          });
        } else {
          this.$store.state.chatFileList[fileData.userid] = [];
          this.$store.state.chatFileList[fileData.userid].push({
            form: form,
            uuid: initId,
            name: fileData.name,
            size: fileData.size,
          });
        }
        if (fileData.name.length >= 15) {
          this.fileName = fileData.name.substring(0, 15) + "...";
        } else {
          this.fileName = fileData.name;
        }
        this.fileSuffix = suffix;
        this.$nextTick(() => {
          setTimeout(() => {
            //节点渲染完成后,canvas生成文件图片
            _this
              .getPic(_this.$refs.imageFileSrc.src, _this.fileName)
              .then((canvas) => {
                let url = canvas.toDataURL();
                document.execCommand(
                  "insertHTML",
                  false,
                  `<img type="_file" uuid="${initId}" src="${url}"/>`
                );
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        });
      });
    },
    // 复制
    copyValue(event) {
      if (event) {
        event.preventDefault();
      }
      this.$emit("copyShowClick", false);
      this.$store.state.copyValue = this.copyText;
      // this.$store.state.copyValue = this.htmlDecodeByRegExp(
      //   this.$utilJs.returnEncodeBr(this.copyText)
      // );
      // 到粘贴板
      // 2022/6/21空内容复制判断
      if (this.copyText == "") {
        this.$Message.warning("复制内容为空");
        return;
      }
      if (this.copyText.includes("<img")) {
        //复制含有图片
        this.$copyText(this.$store.state.copyValue).then(
          //clipboard2复制后原本选区会消失
          (e) => {
            // success
            console.log(e);
            if (this.copyText != "") {
              this.$Message.warning("内容已复制到粘贴板");
            }
          },
          (e) => {
            // faile
            console.log(e);
          }
        );
      } else {
        document.execCommand("copy");
        this.$Message.warning("内容已复制到粘贴板");
      }
    },
    //获取坐标位置
    getItemCoordinate(e) {
      this.pasteMenuTop = e.clientY - 10 || 0;
      this.pasteMenuLeft = e.clientX - 10 || 0;
    },
    //内容插入光标最后位置
    insertContent(str) {
      //截图焦点判断问题
      var selection = window.getSelection();

      this.$refs.contentInput.focus();

      console.log(this.lastEditRange, 942);
      if (this.lastEditRange) {
        // 存在最后光标对象，选定对象清除所有光标并添加最后光标还原之前的状态
        selection.removeAllRanges();
        selection.addRange(this.lastEditRange);
      }
      var range = selection.createRange
        ? selection.createRange()
        : selection.getRangeAt(0);

      console.log(range, 952);
      // 2022/5/10 zc新增 插入区域不为输入框时取消插入，避免插入错误区域bug
      if (
        range.startContainer.id != "contentInput" &&
        range.startContainer.parentNode.id != "contentInput"
      ) {
        return;
      }
      var hasR = range.createContextualFragment(str);
      var hasR_lastChild = hasR.lastChild;

      console.log(hasR, hasR_lastChild, 961);

      while (
        hasR_lastChild &&
        hasR_lastChild.nodeName.toLowerCase() == "br" &&
        hasR_lastChild.previousSibling &&
        hasR_lastChild.previousSibling.nodeName.toLowerCase() == "br"
      ) {
        var e = hasR_lastChild;
        hasR_lastChild = hasR_lastChild.previousSibling;
        hasR.removeChild(e);
      }
      // if($(range.commonAncestorContainer).attr("name") == "contentInput"){
      range.insertNode(hasR);
      if (hasR_lastChild) {
        range.setEndAfter(hasR_lastChild);
        range.setStartAfter(hasR_lastChild);
      }
      range.collapse(false);
      selection.removeAllRanges();
      selection.addRange(range);
      // }
      // 记录最后光标对象
      this.lastEditRange = selection.getRangeAt(0);
    },
    editEleClick() {
      var selection = getSelection();
      if (!selection) {
        return;
      }
      // 设置最后光标对象
      this.lastEditRange = selection.getRangeAt(0);
      // console.log(this.lastEditRange,'光标')
    },
    //发送消息上传文件
    uploadFile(fileInfo, index) {
      console.log(fileInfo, index, 999999999);
      var _this = this;
      let initId = this.$func.uuid();
      let isServiceAcc = isService ? 1 : 0;
      let table =
        _this.toInfo.isGroup == "0"
          ? _this.sqlTable.privateList
          : _this.sqlTable.messageList;
      let sdfs = _this.operationalDatabase(
        `REPLACE INTO ${table}(name,receiveId,sendId,type,value,time,messageId,isRead,isSuccessSend,isDownLoad,DownLoadId,duration,isServiceAcc,isByRead)
        VALUES('${_this.myInfo.name}','${_this.toInfo.id}','${_this.myInfo.id
        }','file',
        '${fileInfo.name
        }','${new Date().getTime()}','${initId}','1','1','0','先存本地',
        '${fileInfo.size}',${isServiceAcc}),0;`
      );
      let sendValue = Object.assign(
        {
          uploading: true,
        },
        {
          upload: 1,
        },
        _this.generateMsg(
          "file",
          fileInfo.name,
          initId,
          fileInfo.size,
          0,
          "",
          fileInfo.path || fileInfo.FilePath
        )
      ); //新增文件路径参数
      this.$emit("updateChatList", sendValue);
      // this.$emit('updateChatList',sendValue);
      // _this.chatList[0].unshift(Object.assign({uploading:true},{upload:1},_this.generateMsg("file", fileInfo.name, initId, fileInfo.size,0)));
      this.self_update_session(
        "file",
        "[文件]",
        initId,
        fileInfo.size,
        new Date().getTime()
      );
      let timeout;
      let isUploadCompleted = false;
      let times = parseInt(new Date().getTime()) + parseInt(index);
      this.$upload(
        "api/v1/oim/file/upload.do?times=" + times,
        fileInfo.form,
        (res) => {
          clearTimeout(timeout);
          isUploadCompleted = true;
          this.$set(sendValue, "uploading", false);
          this.$set(sendValue, "progress", 100);
          this.$set(sendValue, "DownLoadId", res.data.id);
          this.$wsSendMsg(
            this.toInfo,
            initId,
            "file",
            {
              id: res.data.id,
              size: fileInfo.size,
              name: fileInfo.name,
              duration: fileInfo.size,
              isDownLoad: "0",
              DownLoadId: res.data.id,
              gender: this.myInfo.gender || "1",
              head: this.myInfo.headImage || "",
            },
            this.ws
          );
        },
        (res) => {
          clearTimeout(timeout);
          console.log("error");
          console.log(res);
        }
      );

      function getProgress() {
        setTimeout(() => {
          getProgress_axios({ filename: times })
            .then((res) => {
              let progress = (res.progress / res.size) * 100;
              if (progress >= 100) {
                console.log(res, "上传完成");
                this.$set(sendValue, "progress", 100);
              } else if (progress >= 0) {
                console.log(res, "上传中");
                if (!isUploadCompleted) {
                  timeout = setTimeout(() => {
                    getProgress();
                  }, 1500);
                }
                this.$set(sendValue, "progress", progress.toFixed(2));
              } else {
              }
              console.log("上传进度", progress);
            })
            .catch((error) => {
              clearTimeout(timeout);
              console.log("设置失败", error);
            });
        }, 1000);
      }
      timeout = setTimeout(() => {
        getProgress();
      }, 1500);
    },
    groupNoticeClick() {
      if (this.isDissolve) {
        this.$Message.warning("您不在该群聊中,无法操作");
        return;
      }
      this.$emit("groupNoticeClick");
    },
    controlFn(type) {
      //zk标识，远程控制相关
      // 邀请同屏
      if (type == 9) {
        let info = this.$ShareScreenAssistance("InviteUser", [
          `${this.toInfo.id}_PC`,
        ]);
        console.log(info, "邀请同屏");
        info = JSON.parse(info);
        if (info.return_code === "FALSE") {
          this.$message({
            message: info.return_msg,
            type: "warning",
          });
          // 未设置同屏
          this.$emit("screenFn", 0);
        } else {
          // 已设置同屏
          this.$emit("screenFn", 1);
        }
        return;
      }
      let initid = this.$func.uuid();
      this.ws.send(
        this.$publicSend(initid, "1.101", "1.1.0016", {
          userId: this.toInfo.id,
        })
      );
      this.$store.commit("Is_MacAddress_Common", type);
      this.$emit("controlFn", type);
    },
    controlActive() {
      if (!this.$store.state.connectRemoteServer) {
        this.$message({
          message: "远程服务连接中，请稍后重试",
          type: "warning",
        });
        this.$remoteControlConnect();
        return;
      }
      this.$emit("controlActive");
    },
    // 重点语录
    quotations() {
      this.$emit("queryQuotations");
    },
    //index --->1为搜索,其他不需要参数
    operationalDatabase(statements, index) {
      let to = JSON.stringify({
        Sqlstr: statements,
      });
      return arguments[1]
        ? JSON.parse(this.$shellSQL(to, index))
        : JSON.parse(this.$shellSQL(to));
    },
    //聊天列表生成
    generateMsg(type, value, msgId, duration, isDownLoad, DownLoadId, path) {
      console.log(value, 1180);
      return {
        type: type,
        value: value,
        messageId: msgId,
        sendId: this.myInfo.id,
        sendName: this.myInfo.name,
        name: this.myInfo.name,
        receiveId: this.toInfo.id,
        receiveName: this.toInfo.name,
        isGroup: this.toInfo.isGroup,
        time: new Date().getTime(),
        duration: duration,
        isRead: "1",
        isSuccessSend: "1",
        isDownLoad: isDownLoad,
        DownLoadId: DownLoadId,
        isInsertFile: false,
        filePath: path, //新增会话复制文件功能
        replay: this.sendReply,
      };
    },
    generateMsg_imgFile(type, value, msgId, duration, isDownLoad, DownLoadId, path) {
      console.log(value, path, 1181);
      return {
        type: type,
        value: path,
        messageId: msgId,
        sendId: this.myInfo.id,
        sendName: this.myInfo.name,
        name: this.myInfo.name,
        receiveId: this.toInfo.id,
        receiveName: this.toInfo.name,
        isGroup: this.toInfo.isGroup,
        time: new Date().getTime(),
        duration: duration,
        isRead: "1",
        isSuccessSend: "0",
        isDownLoad: isDownLoad,
        DownLoadId: DownLoadId,
        isInsertFile: false,
        filePath: path, //新增会话复制文件功能
        replay: this.sendReply,
        just: true,
        justValue: path,
      };
    },
    //群设置
    updateMessageFree() {
      // 新增设置消息免打扰接口
      // type: 0 个人 1 群
      // option: 操作:1:增加,2:删除
      // times: 勿扰截止时间(预留)
      this.messageFree = !this.messageFree;
      let type = this.toInfo.isGroup == "1" ? 1 : 0;
      let option = this.messageFree ? 1 : 2;
      setUserDnd({
        userId: this.myInfo.id,
        objectId: this.toInfo.id,
        type: type,
        option: option,
      })
        .then((res) => {
          if (res.result === 200) {
            console.log("消息免打扰", res);
            this.$Message.success(res.data);
            this.$emit("updateMessageFree", this.messageFree);
            this.tipFlag = !this.tipFlag; //zk新增禁用/启用提示
          }
        })
        .catch((error) => {
          console.log(error, "error");
        });
    },
    toGroupFunction(index, activeRecords) {
      this.$emit("toGroupFunction", index, activeRecords);
    },
    contentBlur() {
      this.contentFocus = false;
      var selection = window.getSelection();
      // 设置最后光标对象
      this.lastEditRange = selection.getRangeAt(0);
      this.$store.state.chatInputContent[this.toInfo.id] =
        this.$refs.contentInput.innerHTML;
      // console.log('光标位置',this.lastEditRange);
    },
    //鼠标右键
    copyRignt(e) {
      let value = this.$store.state.copyValue;
      // if(value == null) return;
      this.getItemCoordinate(e);
      this.$emit("copyShowClick", true);
      this.$forceUpdate();
      this.copyText = "";
      if (
        this.getSelectionContainerElem() &&
        this.getSelectionContainerElem() != ""
      ) {
        this.copyText = this.getSelectionContainerElem();
      }
    },
    //获取选区dom
    getSelectionContainerElem() {
      var range = window.getSelection().getRangeAt(0);
      var container = document.createElement("div");
      container.appendChild(range.cloneContents());
      console.log(range, container.innerHTML, 124777);
      return this.$utilJs.changeBrNbsp(container.innerHTML);
    },
    htmlRegExp(str) {
      //过滤除img、br以外标签
      var output = str.replace(/<(?!img|br)(([\s\S])*?)>/g, "&lt;$1&gt;");
      //以|$为界，分隔字符串
      output = output.replace(/</g, "|$<");
      output = output.replace(/>/g, ">|$");
      if (output.indexOf("|$") < 0) {
        output = this.$utilJs.returnBrNbsp(output);
      } else {
        var arr = output.split("|$");
        arr.forEach((item) => {
          //不是img标签的，还原空格换行
          if (item.indexOf("<img") < 0) {
            this.$utilJs.returnBrNbsp(item);
          }
        });
        output = arr.join("");
      }
      return output;
    },
    // html编码
    htmlEncodeByRegExp(html) {
      var temp = document.createElement("div");
      temp.textContent != undefined
        ? (temp.textContent = html)
        : (temp.innerText = html);
      var output = temp.innerHTML;
      temp = null;
      return output;
    },
    //点击粘贴
    copyMain(event) {
      event.preventDefault();

      this.$emit("copyShowClick", false);
      let _this = this;
      let infs = this.$shell("GetClipboardData", []);
      infs = eval("(" + infs + ")");
      console.log(infs, 1289);
      // console.log(infs, "粘贴返回内容");
      let pcFileList = [];
      if (infs.return_code === "TRUE") {
        //判断文件大小是否超过500M，超过后无法发送FileLength
        this.$fileBigChoice(infs.return_data.data);
        //新增替换文件名错为路径的问题
        for (let item of infs.return_data.data) {
          if (item.FileName && item.FileName.indexOf("/") != -1) {
            item.FileName = item.FileName.substring(
              item.FileName.lastIndexOf("/") + 1
            );
          }
        }
        if (infs.return_data.formats == "Text") {
          //zk1228标识，粘贴文本内容
          try {
            var obj = JSON.parse(infs.return_data.data);
            if (typeof obj == "object" && obj.type && obj.type == "copyImage") {
              let value = obj;
              document.execCommand(
                "insertHTML",
                false,
                `<img size="${value.size}" DownLoadId="${value.DownLoadId}" draggable="false" suffix='png' src="${value.value}" type="copyImage" style='max-width:8em;max-height:6em;'/>`
              );
            } else {
              document.execCommand(
                "insertHTML",
                false,
                this.htmlRegExp(infs.return_data.data)
              );
              return false;
            }
          } catch (e) {
            document.execCommand(
              "insertHTML",
              false,
              this.htmlRegExp(infs.return_data.data)
            );
          }
          // this.insertContent(this.toExpression(this.$utilJs.returnBrNbsp(this.htmlEncodeByRegExp(infs.return_data.data))));
        } else if (infs.return_data.formats == "Bitmap") {
          document.execCommand(
            "insertHTML",
            false,
            `<img draggable="false" suffix='png' src='${infs.return_data.data}' type="img" style='max-width:8em;max-height:6em;'>`
          );
          // this.insertContent(`<img draggable="false" suffix='png' src='${infs.return_data.data}' type="img" style='max-width:8em;max-height:6em;'>`);
        } else if (infs.return_data.formats == "FileDrop") {
          if (_this.updateDropState || _this.isInsertFile) {
            _this.$Message.warning("文件处理中,请稍后");
            return;
          }
          let pcFileList = infs.return_data.data;
          // 判断是否为重复的粘贴文件
          this.fielIsRepeat(pcFileList, "FileDrop");

          function insertFileItem(fileInfo, i) {
            return new Promise((resolve, reject) => {
              _this.isInsertFile = true;
              _this.$emit("updateDropState", true);
              try {
                let suffix = fileInfo.FileName.toLowerCase()
                  .split(".")
                  .splice(-1);
                let initId = _this.$func.uuid();
                if (_this.$store.state.chatFileList[_this.toInfo.id]) {
                  _this.$store.state.chatFileList[_this.toInfo.id].push({
                    path: fileInfo.FileDrop,
                    uuid: initId,
                    name: fileInfo.FileName,
                    size: fileInfo.FileLength,
                  });
                } else {
                  _this.$store.state.chatFileList[_this.toInfo.id] = [];
                  _this.$store.state.chatFileList[_this.toInfo.id].push({
                    path: fileInfo.FileDrop,
                    uuid: initId,
                    name: fileInfo.FileName,
                    size: fileInfo.FileLength,
                  });
                }
                if (fileInfo.FileName.length >= 15) {
                  _this.fileName =
                    fileInfo.FileName.substring(0, 15) + "..." + suffix;
                } else {
                  _this.fileName = fileInfo.FileName;
                }
                _this.fileSuffix = _this.checkType(suffix);
                _this.$nextTick(() => {
                  setTimeout(() => {
                    //节点渲染完成后,canvas生成文件图片
                    _this
                      .getPic(_this.$refs.imageFileSrc.src, _this.fileName)
                      .then((canvas) => {
                        let url = canvas.toDataURL();
                        document.execCommand(
                          "insertHTML",
                          false,
                          `<img type="_file" uuid="${initId}" src="${url}"  _filepath="${fileInfo.FileDrop}"/>`
                        );
                        if (i == pcFileList.length - 1) {
                          _this.isInsertFile = false;
                          _this.$emit("updateDropState", false);
                        }
                        resolve();
                      })
                      .catch((err) => {
                        _this.isInsertFile = false;
                        _this.$emit("updateDropState", false);
                      });
                  });
                });
              } catch (err) {
                _this.isInsertFile = false;
                _this.$emit("updateDropState", false);
              }
            });
          }
          async function insertFile() {
            for (let i = 0; i < pcFileList.length; i++) {
              console.log(pcFileList[i], "pcFileList");
              await insertFileItem(pcFileList[i], i);
            }
          }
          insertFile();
        }
      }
      console.log(infs, "在新消息中黏贴内容");
      this.$forceUpdate();
    },
    get_2_data(data) {
      let form = new FormData();
      form.append("file", data);
      form.append("userid", this.myInfo.id);
      form.append("toid", this.toInfo.id);
      form.append("toname", this.toInfo.name);
      form.append("isScreenshot", 1);
      return form;
    },
    //处理表情
    toExpression(str) {
      var reg = /\[[\u4e00-\u9fa5]+\]/g;
      var num = [];
      var imageArr = str.match(reg);
      var imageTrue = [];
      var newArr = [].concat.apply([], this.expression);
      if (imageArr) {
        for (let i = 0, len = imageArr.length; i < len; i++) {
          for (let j = 0, lens = newArr.length; j < lens; j++) {
            if (new RegExp(newArr[j]).test(imageArr[i])) {
              num.push(this.createFaceImage(j));
              imageTrue.push(imageArr[i]);
              break;
            }
          }
        }
        for (let i in imageTrue) {
          str = str.replace(imageTrue[i], num[i]);
        }
      }
      return str;
    },
    //修改文本内容发送给后台
    textMsg(myMsg) {
      console.log(myMsg, 1452);
      let regLess = /(\<div\>\<br\>\<\/div\>)*$/g; //去除末尾无意义换行
      // myMsg = myMsg.replace(/\u200B/g, "");   //  去除 零宽字符&#8203;   0713 新增
      myMsg = myMsg.replace(regLess, "");
      myMsg = myMsg;
      // console.log(myMsg)
      let reg = /\<img src=['"]static(.+?)\>/g; //匹配图片
      var imgArr = myMsg.match(reg);
      var regx = /\d+\.gif/g; //匹配gif
      var a = [];
      var sendToAndior = myMsg;
      if (imgArr) {
        for (let i = 0, len = imgArr.length; i < len; i++) {
          let sdn = imgArr[i].match(regx);
          let ins = parseInt(sdn[0].replace(".gif", "")); //获取图片数字
          a.push(ins);
        }
        // console.log(a)
        for (let i = 0, len = imgArr.length; i < len; i++) {
          //找到图片描述
          let m = Math.floor(a[i] / 36);
          let q = a[i] % 36;
          sendToAndior = sendToAndior.replace(
            imgArr[i],
            "[" + this.expression[m][q] + "]"
          );
        }
      }
      //找到非<br>div
      // let regAdd = /\<div\>[^\<]*\<\/div\>/g;
      // let addArr = Array.from(new Set(sendToAndior.match(regAdd)));
      // for (let i in addArr) {
      // 	let arrtest=addArr[i].replace(/-/g,'/\-/')
      // 	let regh = new RegExp(arrtest,'gim');
      // 	let regDiv = /\<div\>|\<\/div\>/g;
      // 	let str = addArr[i].replace(regDiv, '');
      // 	sendToAndior = sendToAndior.replace(regh, str);
      // }
      // console.log(sendToAndior,'文本内容')
      return sendToAndior;
    },
    htmlDecodeByRegExp(text) {
      var temp = document.createElement("div");
      //2.然后将要转换的字符串设置为这个元素的innerHTML(ie，火狐，google都支持)
      temp.innerHTML = text;
      //3.最后返回这个元素的innerText或者textContent，即得到经过HTML解码的字符串了。
      var output = temp.innerText || temp.textContent;
      temp = null;
      console.log("转换的字符串", output);
      return output;
    },
    returnEncodeBr(str) {
      str = str.replace(/<br>/g, "\n");
      str = str.replace(/&nbsp;/g, "\t");
      return str;
    },
    //消息分段函数
    lengthLimit(value) {
      //zk修改，分段发送第二版
      console.log(value, 1511);
      var temp = value
        .replace(/\<div\>/g, "<br>")
        .replace(/\<\/div\>/g, "<br>")
        .replace(/(\<br\>)+/g, "<br>");
      temp = temp.split("<br>");
      var tempStr = temp.join(""); //去<br>
      var tempValue = tempStr
        .replace(/&nbsp;/g, " ")
        .replace(/&lt;/g, "<")
        .replace(/&gt;/g, ">")
        .replace(/&amp;/g, "&"); //全替换
      let count = parseInt(tempValue.length / this.maxMessagrLength);
      let indexList = []; //保存特殊符号的下标
      //获取&amp;下标
      temp = value
        .replace(/&nbsp;/g, " ")
        .replace(/&gt;/g, ">")
        .replace(/\<div\>/g, "<br>")
        .replace(/\<\/div\>/g, "<br>")
        .replace(/(\<br\>)+/g, "<br>");
      temp = temp.split("<br>");
      var newTempStr = temp.join(""); //去<br>
      var rawList = this.$getAllIndex(newTempStr, "&amp;");
      for (let i in rawList) {
        rawList[i] = rawList[i] - i * 4;
      }
      //对<的处理，<坐标
      var newVal = tempStr
        .replace(/&nbsp;/g, " ")
        .replace(/&gt;/g, ">")
        .replace(/&amp;/g, "&"); //不替换左括号
      var newList = this.$getAllIndex(newVal, "&lt;"); //&lt;在除他以外全部替换的下标
      let tempCount = 0;
      for (let i = 0; i < newList.length; i++) {
        if (rawList.indexOf(newList[i]) == -1) {
          //新增
          newList[i] = newList[i] - i * 3; //全部替换之后，用户输入的<的位置
          indexList.push({ type: "&lt;", index: newList[i] });
          tempCount++;
        }
      }
      //对br的处理
      temp = value
        .replace(/&nbsp;/g, " ")
        .replace(/&lt;/g, "<")
        .replace(/&gt;/g, ">")
        .replace(/&amp;/g, "&")
        .replace(/\<div\>/g, "<br>")
        .replace(/\<\/div\>/g, "<br>")
        .replace(/(\<br\>)+/g, "<br>");
      var brList = this.$getAllIndex(temp, "<br>");
      for (let i = 0; i < brList.length; i++) {
        if (i > 0) {
          brList[i] = brList[i] - i * 4; //全部替换之后，用户输入的<的位置
        }
        if (newList.indexOf(brList[i]) == -1) {
          indexList.push({ type: "<br>", index: brList[i] });
        }
      }
      var finalList = [];
      for (let i = 0; i <= count; i++) {
        //准备好list
        finalList.push({
          num: i,
          arr: [],
        });
      }
      // 换算在分段之后的下标值
      for (let i in indexList) {
        let num = parseInt(indexList[i].index / this.maxMessagrLength);
        let index = indexList[i].index % this.maxMessagrLength;
        for (let j in finalList) {
          if (finalList[j].num == num) {
            finalList[j].arr.push({
              type: indexList[i].type,
              index,
            });
          }
        }
      }
      //剩下的&,空格在截取之后的字符串中修改
      let subList = []; //存放截取后的字符串,传给后台的
      for (var i = 0; i <= count; i++) {
        let start = i * this.maxMessagrLength;
        let end =
          (i + 1) * this.maxMessagrLength > tempValue.length
            ? tempValue.length
            : (i + 1) * this.maxMessagrLength;
        let str = tempValue.substring(start, end); //截取
        let ampList = this.$getAllIndex(str, "&");
        let nbspList = this.$getAllIndex(str, " ");
        for (let j in finalList) {
          //将其他特殊符号的下标存入
          if (finalList[j].num == i) {
            for (let m in ampList) {
              finalList[j].arr.push({
                type: "&amp;",
                index: ampList[m],
              });
            }
            for (let n in nbspList) {
              finalList[j].arr.push({
                type: "&nbsp;",
                index: nbspList[n],
              });
            }
          }
        }
        subList.push(str);
      }
      //对finalList按照index排序，根据下标从大到小排，也就是字符串从后往前还原，不用计算下标
      for (let i in finalList) {
        for (let m = 0; m < finalList[i].arr.length - 1; m++) {
          for (let j = 0; j < finalList[i].arr.length - 1 - m; j++) {
            let tempObj;
            if (finalList[i].arr[j].index <= finalList[i].arr[j + 1].index) {
              tempObj = finalList[i].arr[j + 1];
              finalList[i].arr[j + 1] = finalList[i].arr[j];
              finalList[i].arr[j] = tempObj;
            }
          }
        }
      }
      for (let i in subList) {
        for (let j in finalList) {
          if (i == finalList[j].num) {
            for (let m in finalList[j].arr) {
              let tempArr = subList[i].split("");
              if (finalList[j].arr[m].type != "<br>") {
                tempArr.splice(
                  finalList[j].arr[m].index,
                  1,
                  finalList[j].arr[m].type
                );
              } else {
                tempArr.splice(
                  finalList[j].arr[m].index,
                  0,
                  finalList[j].arr[m].type
                );
              }
              subList[i] = tempArr.join("");
            }
          }
        }
      }

      console.log(subList, "分段之后的消息");
      return subList;
    },
    //发送消消息
    sendMsg(type) {
      // 判断发送间隔
      if (this.sendGap) {
        this.$Message.warning("请稍后再发送");
        return;
      }
      this.sendGap = setTimeout(() => {
        //发送间隔
        clearTimeout(this.sendGap);
        this.sendGap = null;
      }, 500);
      if (this.isDissolve) {
        this.$Message.warning("您不在该群聊中,无法操作");
        return;
      }
      // 判断是否为客服状态
      if (this.personalStatus == 4) {
        this.$Message.warning("离线状态无法发送消息");
        return;
      }
      var _this = this;
      const toInfo = JSON.parse(JSON.stringify(_this.toInfo)); //克隆发送对象信息
      if (this.isService && toInfo.isGroup == 1) {
        this.$Message.warning("客服状态下无法发送群消息");
        return;
      }
      // let rawValue = this.$refs.contentInput.innerHTML; //输入框原始内容
      let value = this.textMsg(this.$refs.contentInput.innerHTML);
      console.log('输入框原始值', value);
      let child = this.$refs.contentInput.childNodes;

      // let newA = value.split(" ");
      // console.log(newA, 1695);
      // var typeReg = /type=[\'\"]?([^\'\"]*)[\'\"]?/;
      let nbspAll = value.replace(/&nbsp;/g, "");
      if (!nbspAll.trim()) {
        this.$Message.warning("不能发送空白信息");
        this.$refs.contentInput.innerHTML = "";
        return;
      }
      let newValue = this.toExpression(this.$utilJs.regUrl(value, 1));
      let isServiceAcc = this.isService ? 1 : 0;
      var arr = [];
      var imgArr = [];
      var textArr = [];
      var newValueArr = [];
      var filesArr = [];
      var imgReg = /<img.*?(?:>|\/>)/gi;
      var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/;
      var suffixReg = /suffix=[\'\"]?([^\'\"]*)[\'\"]?/;
      var typeReg = /type=[\'\"]?([^\'\"]*)[\'\"]?/;
      var uuidReg = /uuid=[\'\"]?([^\'\"]*)[\'\"]?/;
      var pathReg = /path=[\'\"]?([^\'\"]*)[\'\"]?/;
      var DownLoadIdReg = /downloadid=[\'\"]?([^\'\"]*)[\'\"]?/;
      var sizeReg = /size=[\'\"]?([^\'\"]*)[\'\"]?/;
      let dowArr = [];
      let typeArr = [];
      console.log('输入框子dom',[child]);
      child.forEach((i) => {
        let dom = document.createElement("div");
        dom.appendChild(i.cloneNode(true));
        let a = dom.innerHTML;
        // let va1 = this.textMsg(i);
        // 2022/7/12 新增判断 避免零宽度字符"&#8203;"进入发送消息
        if (a == "​") {
          return;
        }
        dowArr.push(a);
        let type = a.match(typeReg);
        typeArr.push(type);
        console.log('输入框子dom值', a, type);
        if (type != null) {
          if (type[1] == "img") {
            var suffix = a.match(suffixReg);
            var src = a.match(srcReg);
            imgArr.push({
              src: src[1],
              suffix: suffix[1],
              type: type[1],
            });
          } else if (type[1] == "file" || type[1] == "_file") {
            var uuid = a.match(uuidReg);
            imgArr.push({
              uuid: uuid[1],
              type: type[1],
            });
          } else if (type[1] == "copyImage") {
            var suffix = a.match(suffixReg);
            var src = a.match(srcReg);
            var DownLoadId = a.match(DownLoadIdReg);
            var size = a.match(sizeReg);
            imgArr.push({
              src: src[1],
              suffix: suffix[1],
              type: type[1],
              DownLoadId: DownLoadId[1],
              size: size[1],
            });
          }
        }
      });

      console.log(imgArr, "发送文件的列表。。。");
      if (imgArr.length > 0) {
        newValueArr = newValue.split(imgReg);
        textArr = value.split(imgReg);
        console.log('发送的的值', [newValue,newValueArr, dowArr, typeArr]);

        dowArr.forEach((t, i) => {
          console.log(t, 1815);
          // console.log(t.includes('<img'));
          if (!t.includes("<img")) {
            console.log(t, 1817);
            t = this.textMsg(t);
            let reg = /<[^>]+>|&[^>]+;/g;
            let trim = t.replace(reg, "");
            let textVal = t;

            if (t.trim() != "" && trim.trim() != "") {
              let initKey = this.$func.uuid();
              console.log(type, 1825);
              this.self_update_session(
                type,
                textVal,
                initKey,
                1,
                new Date().getTime()
              );
              let sendValue = this.toExpression(this.$utilJs.regUrl(t, 1));
              sendValue = `<div style="font-size:${this.sizeValue}px;color:${this.colorValue};font-weight:${this.boldValue}">${sendValue}</div>`;

              this.$emit(
                "updateChatList",
                this.generateMsg("text", sendValue, initKey, 1)
              );
              this.$emit("storageSqlSendText", {
                //这里存本地数据库时间为当前时间
                receiveId: toInfo.id,
                sendId: this.myInfo.id,
                sendName: this.myInfo.name,
                receiveName: toInfo.name,
                type: "text",
                value: textVal,
                time: new Date().getTime(),
                messageId: initKey,
                isGroup: toInfo.isGroup,
                fontSize: this.fontStyle ? this.fontStyle : this.sizeValue,
                headUrl: this.myInfo.head || "",
                replay: this.sendReply,
                isServiceAcc: isServiceAcc,
              });

              let nowTime = new Date().getTime();
              console.log("现在的时间：", nowTime);
              // socket向服务端发送信息内容
              this.$wsSendMsg(
                toInfo,
                initKey,
                "text",
                {
                  text: t,
                  gender: this.myInfo.gender || "1",
                  head: this.myInfo.headImage || "",
                  fontSize: this.fontStyle ? this.fontStyle : this.sizeValue,
                },
                this.ws
              );
              this.$forceUpdate();
            }
          } else {
            if (typeArr[i] != null) {
              console.log(t, 1874);

              let dt = t.match(typeReg)[1];
              let src = t.match(srcReg)[1];
              // console.log(dt, suffix, src, 1877777);
              if (dt == "img") {
                let suffix = t.match(suffixReg)[1];
                let base = src;

                let img = src.replace(/^data\:.{1,40}base64\,/gi, "");
                let blobFile = _this.$utilJs.dataURItoBlob(base);
                let initid = _this.$func.uuid();
                let table =
                  toInfo.isGroup == "0"
                    ? _this.sqlTable.privateList
                    : _this.sqlTable.messageList;
                console.log(blobFile, 1862);
                if (toInfo.isGroup == "0") {

                  // 2022/5/26 zc修改 图片先入库
                  let res111 = _this.operationalDatabase(
                    `REPLACE INTO ${table}
                        (name,receiveId,sendId,type,value,smallValue,time,messageId,isRead,isSuccessSend,isDownLoad,DownLoadId,duration,isServiceAcc,isByRead)
                        VALUES('${_this.myInfo.name}','${toInfo.id}','${_this.myInfo.id
                    }','image','','',
                        '${new Date().getTime()}','${initid}','1','0','0','1','32',${isServiceAcc},0);`
                  );
                  console.log(res111, 1872);


                } else {
                  // 2022/5/26 zc修改 图片先入库
                  let res111 = _this.operationalDatabase(
                    `REPLACE INTO ${table}
                        (name,receiveId,sendId,type,value,smallValue,time,messageId,isRead,isSuccessSend,isDownLoad,DownLoadId,duration,isServiceAcc)
                        VALUES('${_this.myInfo.name}','${toInfo.id}','${_this.myInfo.id
                    }','image','','',
                        '${new Date().getTime()}','${initid}','1','0','0','1','32',${isServiceAcc});`
                  );
                  console.log(res111, 1887);
                }
                let infs = _this.$shell("SaveFileStream", [
                  _this.myInfo.id,
                  img,
                  suffix,
                ]);
                console.log("返回值1887", infs);
                infs = JSON.parse(infs);

                if (infs.return_code === "TRUE") {
                  _this.self_update_session(
                    "image",
                    "[图片]",
                    initid,
                    32,
                    new Date().getTime()
                  );
                  let tempObj = _this.generateMsg(
                    "image",
                    infs.return_msg,
                    initid,
                    32,
                    0
                  );
                  tempObj.smallValue = infs.return_msg;
                  _this.$emit("updateChatList", tempObj);

                  // let tttt = _this.operationalDatabase(
                  //   `REPLACE INTO ${table}
                  //   (name,receiveId,sendId,type,value,smallValue,time,messageId,isRead,isSuccessSend,isDownLoad,DownLoadId,duration,isServiceAcc,isByRead)
                  //   VALUES('${_this.myInfo.name}','${toInfo.id}','${
                  //     _this.myInfo.id
                  //   }','image','${infs.return_msg}','${infs.return_msg}',
                  //   '${new Date().getTime()}','${initid}','1','1','0','1','32',${isServiceAcc},0);`
                  // );
                  // 2022/5/26 zc修改 外壳返回后再更新数据库图片
                  _this.operationalDatabase(
                    `UPDATE ${table} SET value = "${infs.return_msg}" ,smallValue = "${infs.return_msg}",isSuccessSend = '1' WHERE messageId = "${initid}"`
                  );

                  console.log("存图片", new Date().getTime(), 1923);
                  let form = _this.get_2_data(blobFile);
                  console.log(base, blobFile, "图片上传==>只有截图触发");
                  _this.$upload(
                    "api/v1/oim/image/upload.do",
                    form,
                    (info) => {
                      console.log(
                        toInfo,
                        "上传的返回值==============>>>>>>>>>>>>>>>>"
                      );
                      if (info.result == 4) {
                        console.log(1933);
                        //上传失败
                        this.uploadImgErr(table, initid, base);
                        return;
                      }
                      // 新增发送完截图会话上移
                      _this.$emit("newSessionSort");
                      _this.$wsSendMsg(
                        toInfo,
                        initid,
                        "image",
                        {
                          id: info.data.id,
                          size: info.data.size,
                          name: _this.myInfo.id + new Date().getTime() + ".jpg",
                          duration: 32,
                          gender: _this.myInfo.gender || "1",
                          head: _this.myInfo.headImage || "",
                        },
                        _this.ws
                      );
                      if (toInfo.id == _this.toInfo.id) {
                        for (let i in this.currentTempChat[0]) {
                          if (this.currentTempChat[0][i].messageId == initid) {
                            this.currentTempChat[0][i].DownLoadId =
                              info.data.id;
                            break;
                          }
                        }
                        for (let i in this.currentTempChat[1]) {
                          if (this.currentTempChat[1][i].messageId == initid) {
                            this.currentTempChat[1][i].DownLoadId =
                              info.data.id;
                            break;
                          }
                        }
                      }
                    },
                    (err) => {
                      console.warn("error==>", err);
                      console.log(1970);
                      //新增 消息发送5s后无返回，判定为发送消息失败
                      setTimeout(_this.uploadImgErr(table, initid, base), 5000);
                    }
                  );
                  _this.$forceUpdate();
                }
              } else if (dt == "file") {
                console.log(file, 1962);
                let uuid = t.match(uuidReg)[1];
                for (
                  let j = 0;
                  j < this.$store.state.chatFileList[toInfo.id].length;
                  j++
                ) {
                  if (
                    this.$store.state.chatFileList[toInfo.id][j].uuid == uuid
                  ) {
                    this.uploadFile(
                      this.$store.state.chatFileList[toInfo.id][j],
                      j
                    );
                    break;
                  }
                }
              } else if (dt == "_file") {
                console.log("_file");
                let uuid = t.match(uuidReg)[1];
                console.log(uuid, 1997);
                for (
                  let j = 0;
                  j < this.$store.state.chatFileList[toInfo.id].length;
                  j++
                ) {
                  if (
                    this.$store.state.chatFileList[toInfo.id][j].uuid == uuid
                  ) {
                    this.pcUploadFile(
                      this.$store.state.chatFileList[toInfo.id][j],
                      j
                    );
                    break;
                  }
                }
              } else if (dt == "copyImage") {
                let DownLoadId = t.match(DownLoadIdReg)[1];
                let size = t.match(sizeReg)[1];
                let initid = _this.$func.uuid();
                _this.self_update_session(
                  "image",
                  "[图片]",
                  initid,
                  32,
                  new Date().getTime()
                );
                _this.$emit(
                  "updateChatList",
                  _this.generateMsg("image", src, initid, 32, 0)
                );
                let table =
                  toInfo.isGroup == "0"
                    ? _this.sqlTable.privateList
                    : _this.sqlTable.messageList;
                let tttt = _this.operationalDatabase(
                  `REPLACE INTO ${table}(name,receiveId,sendId,type,value,time,messageId,isRead,isSuccessSend,isDownLoad,DownLoadId,duration,isServiceAcc,isByRead)
                   VALUES('${_this.myInfo.name}','${toInfo.id}','${_this.myInfo.id
                  }','image',
                  '${src}','${new Date().getTime()}',
                  '${initid}','1','1',${DownLoadId},'1','32',${isServiceAcc},0);`
                );
                // 新增发送完截图会话上移
                _this.$emit("newSessionSort");
                console.log(DownLoadId, "imgArr[i].DownLoadId");
                _this.$wsSendMsg(
                  toInfo,
                  initid,
                  "image",
                  {
                    id: DownLoadId,
                    size: "",
                    name: _this.myInfo.id + new Date().getTime() + ".jpg",
                    duration: 32,
                    gender: _this.myInfo.gender || "1",
                    head: _this.myInfo.headImage || "",
                  },
                  _this.ws
                );
              }
            } else {
              console.log(t, 2041);
              let reg = /<\/?.+?\/?>/g;
              var imgReg = /<img.*?(?:>|\/>)/gi;
              let faceArr = t.match(imgReg) ? t.match(imgReg) : [];
              let trim = t.replace(reg, "");
              console.log(trim, "发送消息");
              if ((t.trim() != "" && trim.trim() != "") || faceArr.length > 0) {
                let value = this.textMsg(t);
                console.log(value, 2051);
                let subList = this.lengthLimit(value);
                console.log(subList, 2049);
                this.userValue = this.$refs.contentInput.innerHTML = "";
                for (let i = 0; i < subList.length; i++) {
                  let initKey = this.$func.uuid(); //zk注释，每次for生成新的initKey
                  this.self_update_session(
                    type,
                    this.textMsg(subList[i]),
                    initKey,
                    1,
                    new Date().getTime()
                  );
                  //本地聊天框分段显示
                  this.$emit(
                    "updateChatList",
                    this.generateMsg(
                      "text",
                      `<div style="font-size:${this.sizeValue}px;color:${this.colorValue};font-weight:${this.boldValue}">${subList[i]}</div>`,
                      initKey,
                      1
                    )
                  );
                  this.$emit("storageSqlSendText", {
                    //zk注释，这里存本地数据库时间为当前时间
                    receiveId: toInfo.id,
                    sendId: this.myInfo.id,
                    sendName: this.myInfo.name,
                    receiveName: toInfo.name,
                    type: "text",
                    value: subList[i],
                    time: new Date().getTime(),
                    messageId: initKey,
                    isGroup: toInfo.isGroup,
                    fontSize: this.fontStyle ? this.fontStyle : this.sizeValue,
                    headUrl: this.myInfo.head || "",
                    replay: this.sendReply,
                    isServiceAcc: isServiceAcc,
                  });

                  console.log("this.ws.send", this.ws);
                  this.$wsSendMsg(
                    toInfo,
                    initKey,
                    "text",
                    {
                      //zk注释，向后台发送text消息,bug:请求发送由于响应完成的时间不同，分段消息存入数据库的时间可能跟for执行的顺序不同，导致重新进入时消息乱序
                      text: subList[i],
                      gender: this.myInfo.gender || "1",
                      head: this.myInfo.headImage || "",
                      fontSize: this.fontStyle
                        ? this.fontStyle
                        : this.sizeValue,
                      replay: this.sendReply,
                    },
                    this.ws
                  );
                }

                this.$forceUpdate(); //zk注释
                this.$store.state.chatInputContent[toInfo.id] = "";
              } else {
                this.$Message.warning("不能发送空白信息");
              }
            }
          }
        });

        for (let i = 0; i < textArr.length; i++) {
          textArr[i] = this.textMsg(textArr[i]);
          console.log(textArr[i], 1823);
          let reg = /<[^>]+>|&[^>]+;/g;
          let trim = textArr[i].replace(reg, "");
          let textVal = this.textMsg(newValueArr[i]);
        }
        this.userValue = this.$refs.contentInput.innerHTML = "";
        this.$store.state.chatInputContent[toInfo.id] = "";
        this.$store.state.chatFileList[toInfo.id] = [];
      } else {
        let reg = /<\/?.+?\/?>/g;
        var imgReg = /<img.*?(?:>|\/>)/gi;
        let faceArr = newValue.match(imgReg) ? newValue.match(imgReg) : [];
        let trim = newValue.replace(reg, "");
        console.log("发送消息",[trim]);
        if (
          (newValue.trim() != "" && trim.trim() != "") ||
          faceArr.length > 0
        ) {
          let subList = this.lengthLimit(value);
          this.userValue = this.$refs.contentInput.innerHTML = "";
          for (let i = 0; i < subList.length; i++) {
            let initKey = this.$func.uuid(); //zk注释，每次for生成新的initKey
            this.self_update_session(
              type,
              this.textMsg(subList[i]),
              initKey,
              1,
              new Date().getTime()
            );
            //本地聊天框分段显示
            this.$emit(
              "updateChatList",
              this.generateMsg(
                "text",
                `<div style="font-size:${this.sizeValue}px;color:${this.colorValue};font-weight:${this.boldValue}">${subList[i]}</div>`,
                initKey,
                1
              )
            );
            this.$emit("storageSqlSendText", {
              //zk注释，这里存本地数据库时间为当前时间
              receiveId: toInfo.id,
              sendId: this.myInfo.id,
              sendName: this.myInfo.name,
              receiveName: toInfo.name,
              type: "text",
              value: subList[i],
              time: new Date().getTime(),
              messageId: initKey,
              isGroup: toInfo.isGroup,
              fontSize: this.fontStyle ? this.fontStyle : this.sizeValue,
              headUrl: this.myInfo.head || "",
              replay: this.sendReply,
              isServiceAcc: isServiceAcc,
            });

            console.log("this.ws.send", [this.ws]);
            this.$wsSendMsg(
              toInfo,
              initKey,
              "text",
              {
                //zk注释，向后台发送text消息,bug:请求发送由于响应完成的时间不同，分段消息存入数据库的时间可能跟for执行的顺序不同，导致重新进入时消息乱序
                text: subList[i],
                gender: this.myInfo.gender || "1",
                head: this.myInfo.headImage || "",
                fontSize: this.fontStyle ? this.fontStyle : this.sizeValue,
                replay: this.sendReply,
              },
              this.ws
            );
          }

          this.$forceUpdate(); //zk注释
          this.$store.state.chatInputContent[toInfo.id] = "";

          //发送消息后滚动到底部
          this.$nextTick(()=>{
            this.$emit("backBottom");
            setTimeout(()=>{
              this.$emit('chatScrollToBottom')
            },100)
          })
        } else {
          this.$Message.warning("不能发送空白信息");
        }
      }
      //新增判断 拖拽/粘贴 的时候反应空白时间点击Enter导致文件发送错误的问题
      if (!this.isPasteDrop) {
        this.$store.state.chatFileList[toInfo.id] = [];
        this.isPasteDrop = false;
      }
      // this.$store.state.chatFileList[this.toInfo.id]=[];
      // this.$emit("resetUp_DownFlag") //zk新增，发送消息后重置翻页标记，123已废弃
      this.delReplay();
      this.$store.commit("setToReply", null)
      this.$store.commit("setToReplyTemp", null)
    },
    //更新文件状态
    updatefilePath(id, path) {
      // let tableName = isGroup == '1' ? this.sqlTable.messageList : this.sqlTable.privateList;
      let rep = this.operationalDatabase(
        `UPDATE ${this.sqlTable.messageList} SET isDownLoad='${path}' WHERE messageId='${id}';`
      );
      let repData = this.operationalDatabase(
        `UPDATE ${this.sqlTable.privateList} SET isDownLoad='${path}' WHERE messageId='${id}';`
      );
      console.log(rep, repData, "下载完成");
    },
    pcUploadFile(fileInfo, index) {
      console.log(fileInfo, index, 2449);
      var _this = this;
      var isServiceAcc = this.isService ? 1 : 0;
      let initId = this.$func.uuid();
      const filesize = fileInfo.size / 1024 / 1024 || 0;
      var AllImgExt = ".jpg|.jpeg|.gif|.bmp|.png|.swf|.tiff";
      var extName = fileInfo.name
        .substring(fileInfo.name.lastIndexOf("."))
        .toLowerCase(); //（把路径中的所有字母全部转换为小写）
      let table =
        _this.toInfo.isGroup == "0"
          ? _this.sqlTable.privateList
          : _this.sqlTable.messageList;
      //图片大于5m，走文件发送
      if (AllImgExt.indexOf(extName + "|") == -1 || filesize > 5) {
        // 2022/7/12 修改 因群聊与私聊表字段不同，以下判断区分入库
        if (_this.toInfo.isGroup == "0") {
          let sdfs = _this.operationalDatabase(
            `REPLACE INTO ${table}(name,receiveId,sendId,type,value,time,messageId,isRead,isSuccessSend,isDownLoad,DownLoadId,duration,isServiceAcc,isByRead)
            VALUES('${_this.myInfo.name}','${_this.toInfo.id}','${_this.myInfo.id
            }','file',
            '${fileInfo.name}','${new Date().getTime()}','${initId}','1','1','${fileInfo.path || fileInfo.FilePath
            }','kkdy','${fileInfo.size}',${isServiceAcc},0);`
          );
        } else {
          let sdfs = _this.operationalDatabase(
            `REPLACE INTO ${table}(name,receiveId,sendId,type,value,time,messageId,isRead,isSuccessSend,isDownLoad,DownLoadId,duration,isServiceAcc)
            VALUES('${_this.myInfo.name}','${_this.toInfo.id}','${_this.myInfo.id
            }','file',
            '${fileInfo.name}','${new Date().getTime()}','${initId}','1','1','${fileInfo.path || fileInfo.FilePath
            }','kkdy','${fileInfo.size}',${isServiceAcc});`
          );
        }
        let sendValue = Object.assign(
          {
            uploading: true,
          },
          {
            upload: 1,
          },
          _this.generateMsg(
            "file",
            fileInfo.name,
            initId,
            fileInfo.size,
            0,
            "",
            fileInfo.path || fileInfo.FilePath
          )
        ); //新增文件路径参数
        this.$emit("updateFile", sendValue);
        this.$emit("updateChatList", sendValue);
        // _this.chatList[0].unshift(sendValue);
        this.self_update_session(
          "file",
          "[文件]",
          initId,
          fileInfo.size,
          new Date().getTime()
        );
        console.log(
          "1",
          _this.toInfo.id,
          initId,
          fileInfo.path,
          "文件上传信息"
        );
        let infos = _this.$shell("UpLoadFile", [
          "1",
          _this.toInfo.id,
          initId,
          fileInfo.path,
          parseInt(_this.toInfo.isGroup),
          _this.toInfo.name,
          _this.myInfo.id,
        ]);
        console.log(infos, "文件上传接口返回");
        try {
          infos = JSON.parse(infos);
          if (infos.return_code != "TRUE") {
            _this.$Message.warning(infos.return_msg);
          }
        } catch (err) {
          _this.$set("sendValue", "isDownLoad", 404);
          _this.updatefilePath(initId, 404);
          _this.$Message.warning("上传文件出错,请稍后再试");
        }
      } else {
        if (_this.toInfo.isGroup == "0") {
          let sdfs = _this.operationalDatabase(
            `REPLACE INTO ${table}(name,receiveId,sendId,type,value,smallValue,time,messageId,
          isRead,isSuccessSend,isDownLoad,DownLoadId,duration,isByRead)
            VALUES('${_this.myInfo.name}','${_this.toInfo.id}',
            '${_this.myInfo.id}','image','${fileInfo.path || fileInfo.FilePath
            }',
            '${fileInfo.path || fileInfo.FilePath}','${new Date().getTime()}',
            '${initId}','1','1','0','kkdy','${fileInfo.size}',0);`
          );
        } else {
          let sdfs = _this.operationalDatabase(
            `REPLACE INTO ${table}(name,receiveId,sendId,type,value,smallValue,time,messageId,
          isRead,isSuccessSend,isDownLoad,DownLoadId,duration)
            VALUES('${_this.myInfo.name}','${_this.toInfo.id}',
            '${_this.myInfo.id}','image','${fileInfo.path || fileInfo.FilePath
            }',
            '${fileInfo.path || fileInfo.FilePath}','${new Date().getTime()}',
            '${initId}','1','1','0','kkdy','${fileInfo.size}');`
          );
        }
        let sendValue = Object.assign(
          {
            uploading: true,
            upload: 1,
            smallValue: fileInfo.path || fileInfo.FilePath,
          },
          _this.generateMsg(
            "image",
            fileInfo.path || fileInfo.FilePath,
            initId,
            fileInfo.size,
            0
          )
        );
        this.$emit("updateFile", sendValue);
        this.$emit("updateChatList", sendValue);
        let infos = _this.$shell("UpLoadFile", [
          "0",
          _this.toInfo.id,
          initId,
          fileInfo.path,
          parseInt(_this.toInfo.isGroup),
          _this.toInfo.name,
          _this.myInfo.id,
        ]);
        console.log(infos, "文件上传接口返回", fileInfo.path);
        try {
          infos = JSON.parse(infos);
          if (infos.return_code != "TRUE") {
            _this.$Message.warning(infos.return_msg);
          }
          // 新增发送储存image到本地数据库(包括拖拽/粘贴图片)
          // _this.$emit('storageSqlSendText',{
          // 	receiveId: _this.toInfo.id,
          // 	sendId: _this.myInfo.id,
          // 	sendName: _this.myInfo.name,
          // 	receiveName: _this.toInfo.name,
          // 	type: 'image',
          // 	fileName: fileInfo.name,
          // 	filePath: fileInfo.path,
          // 	time: new Date().getTime(),
          // 	messageId: initId,
          // 	isGroup: _this.toInfo.isGroup,
          // 	fontSize: _this.sizeValue,
          // 	headUrl: _this.myInfo.head || "",
          // });
        } catch (err) {
          _this.$Message.warning("发送图片出错,请稍后再试");
        }
      }
    },
    keyArr(e) {
      var selection = getSelection();
      // 设置最后光标对象
      this.lastEditRange = selection.getRangeAt(0);
      if (this.user_hot_key[4] == 1) {
        if (e.ctrlKey == false && e.keyCode == 13) this.sendMsg("text");
        if (e.ctrlKey == true && e.keyCode == 13) {
          document.execCommand("insertHTML", false, "<br>&ZeroWidthSpace;");
          // document.execCommand('forwardDelete', false);
        }
      } else {
        if (e.ctrlKey == true && e.keyCode == 13) this.sendMsg("text");
      }
      this.$store.state.chatInputContent[this.toInfo.id] =
        this.$refs.contentInput.innerHTML;

      if (this.$refs.contentInput.innerHTML.slice(-1) == "@") {
        //光标前一位是@，唤醒列表
        // 2022/6/27 修改唤醒前判断是否在群内
        if (this.toInfo.isGroup == "1") {
          this.specified(false);
          this.$emit("changeShow", "specified_show", true); //zk修改，让父组件来修改specified_show的值
          this.getSelectionCoords();
        }
      }
      if (this.specified_show) {
        //@列表显示中
        if (!this.$refs.contentInput.innerHTML.includes("@")) {
          //回退键删除@，列表消失
          this.$emit("changeShow", "specified_show", false);
        }
        const i = this.$refs.contentInput.innerHTML.lastIndexOf("@");
        const key = this.$refs.contentInput.innerHTML.slice(i + 1);
        if (key) {
          clearTimeout(this.group_people_gap);
          this.group_people_gap = setTimeout(() => {
            this.group_people_show = this.group_people.filter((item) => {
              return this.$pinyinMatch.match(item, key);
            });
          }, 300);
        }
      }
    },
    content_input_focus() {
      this.contentFocus = true;
      this.$emit("content_input_focus");
    },
    //快捷回复
    quickReply(value) {
      if (this.personalStatus == 4) {
        this.$Message.warning("离线状态无法进行该操作");
        return;
      }
      let initKey = this.$func.uuid();
      this.self_update_session(
        "text",
        this.textMsg(value),
        initKey,
        1,
        new Date().getTime()
      );
      // this.chatList[0].unshift(this.generateMsg("text", value, initKey, 1));
      this.$emit("updateChatList", this.generateMsg("text", value, initKey, 1));
      this.$wsSendMsg(
        this.toInfo,
        initKey,
        "text",
        {
          text: value,
          gender: this.myInfo.gender || "1",
          head: this.myInfo.headImage || "",
        },
        this.ws
      );
      // this.quickShow = false;
      this.$emit("changeShow", "quickShow", false); //zk修改，让父组件来修改quickShow的值
      this.$forceUpdate();
    },
    quickClick() {
      if (this.isDissolve) {
        this.$Message.warning("您不在该群聊中,无法操作");
        return;
      }
      // this.specified_show = false;
      this.$emit("changeShow", "specified_show", false); //zk修改，让父组件来修改specified_show的值
      // this.faceShow = false;
      this.$emit("changeShow", "faceShow", false); //zk修改，让父组件来修改faceshow的值
      // this.quickShow = !this.quickShow;
      this.$emit("changeShow", "quickShow"); //zk修改，让父组件来修改quickShow的值
      this.control_show = false;
    },
    //生成表情图片
    createFaceImage(index) {
      return `<img src='static/image/face/${index}.gif' draggable="false" style="width:1.6em;height:1.6em;vertical-align:bottom;flex-shrink:0;">`;
    },
    //复制粘贴板信息
    pasteEvent(e) {
      // 新增粘贴/拖拽字段
      this.isPasteDrop = true;

      var _this = this;
      e.preventDefault();
      let infs = this.$shell("GetClipboardData", []);
      console.log(infs, 2494);
      infs = eval("(" + infs + ")");
      if (infs.return_code === "TRUE") {
        //判断文件大小是否超过500M，超过后无法发送
        this.$fileBigChoice(infs.return_data.data);
        // 粘贴内容为文字
        if (infs.return_data.formats == "Text") {
          try {
            var obj = JSON.parse(infs.return_data.data);
            if (typeof obj == "object" && obj.type && obj.type == "copyImage") {
              let value = obj;
              document.execCommand(
                "insertHTML",
                false,
                `<img size="${value.size}" DownLoadId="${value.DownLoadId}" draggable="false" suffix='png' src="${value.value}" type="copyImage" style='max-width:8em;max-height:6em;'/>`
              );
            } else {
              document.execCommand(
                "insertHTML",
                false,
                this.htmlRegExp(infs.return_data.data)
              );
              return false;
            }
          } catch (e) {
            // 2022/7/20 修复 原先使用insertContent方法造成图片复制再粘贴变成dom结构base64编码
            document.execCommand(
              "insertHTML",
              false,
              this.htmlRegExp(infs.return_data.data)
            );
            // this.insertContent(this.toExpression(this.$utilJs.returnBrNbsp(this.htmlEncodeByRegExp(infs.return_data.data))));
          }
        } else if (infs.return_data.formats == "Bitmap") {
          document.execCommand(
            "insertHTML",
            false,
            `<img draggable="false" suffix='png' src='${infs.return_data.data}' type="img" style='max-width:8em;max-height:6em;'>`
          );
          // this.insertContent(`<img draggable="false" suffix='png' src='${infs.return_data.data}' type="img" style='max-width:8em;max-height:6em;'>`);
        } else if (infs.return_data.formats == "FileDrop") {
          if (_this.updateDropState || _this.isInsertFile) {
            _this.$Message.warning("文件处理中,请稍后");
            return;
          }
          let filesData = infs.return_data.data || [];
          // 判断是否为重复的粘贴文件
          this.fielIsRepeat(filesData, "FileDrop");
          // let canvasValue = this.textMsg(this.$refs.contentInput.innerHTML);
          // let imgReg = /<img.*?(?:>|\/>)/gi;
          // let canvasArr = canvasValue.match(imgReg)?canvasValue.match(imgReg):[];
          // for(let i = 0; i < canvasArr.length; i++) {
          // 	let str = canvasArr[i].substring(canvasArr[i].indexOf('_filepath=') + 11, canvasArr[i].length - 2);
          // 	for(let item of filesData) {
          // 		if(str == item.FileDrop) {
          // 			filesData.splice(i, 1);
          // 			_this.$Message.warning("文件重复，已过滤");
          // 		}
          // 	}
          // };
          function insertFileItem(fileInfo, i) {
            return new Promise((resolve, reject) => {
              _this.isInsertFile = true;
              _this.$emit("updateDropState", true);
              try {
                let suffix = fileInfo.FileName.toLowerCase()
                  .split(".")
                  .splice(-1);
                let initId = _this.$func.uuid();
                if (_this.$store.state.chatFileList[_this.toInfo.id]) {
                  _this.$store.state.chatFileList[_this.toInfo.id].push({
                    path: fileInfo.FileDrop,
                    uuid: initId,
                    name: fileInfo.FileName,
                    size: fileInfo.FileLength,
                  });
                } else {
                  _this.$store.state.chatFileList[_this.toInfo.id] = [];
                  _this.$store.state.chatFileList[_this.toInfo.id].push({
                    path: fileInfo.FileDrop,
                    uuid: initId,
                    name: fileInfo.FileName,
                    size: fileInfo.FileLength,
                  });
                }
                // if(fileInfo.FileName.length>=15){
                // 	_this.fileName=fileInfo.FileName.substring(0,15)+'...'+suffix;
                // }else{
                // 	_this.fileName=fileInfo.FileName;
                // }
                if (fileInfo.FileName.lastIndexOf(".") >= 15) {
                  _this.fileName =
                    fileInfo.FileName.substring(0, 15) + "...." + suffix;
                } else {
                  _this.fileName = fileInfo.FileName;
                }
                console.log(_this.fileName);
                _this.fileSuffix = _this.checkType(suffix);
                _this.$nextTick(() => {
                  setTimeout(() => {
                    //节点渲染完成后,canvas生成文件图片
                    _this
                      .getPic(_this.$refs.imageFileSrc.src, _this.fileName)
                      .then((canvas) => {
                        let url = canvas.toDataURL();
                        document.execCommand(
                          "insertHTML",
                          false,
                          `<img type="_file" uuid="${initId}" src="${url}" _filepath="${fileInfo.FileDrop}"/>`
                        );
                        if (i == filesData.length - 1) {
                          _this.isInsertFile = false;
                          _this.$emit("updateDropState", false);
                        }
                        resolve();
                      })
                      .catch(() => {
                        _this.isInsertFile = false;
                        _this.$emit("updateDropState", false);
                      });
                  });
                });
              } catch (err) {
                _this.isInsertFile = false;
                _this.$emit("updateDropState", false);
              }
            });
          }
          async function insertFile() {
            for (let i = 0; i < filesData.length; i++) {
              await insertFileItem(filesData[i], i);
            }
          }
          insertFile();
        }
      }
      console.log(infs, "黏贴内容");
      this.$forceUpdate();
      // js原生方法
      // var text;
      // var clp = (e.originalEvent || e).clipboardData;
      // console.log(clp,'复制黏贴');
      // function copyImg(res){
      // 	document.execCommand('insertHTML', false, `<img draggable="false" suffix='png' src='${res}' type="img" style='max-width:8em;max-height:6em;'>`);
      // }
      // function imgReader( item ){
      // 	var blob = item.getAsFile(),
      // 		reader = new FileReader();
      // 		reader.onload = function( e ){
      // 				// console.log(e.target.result);
      // 			if(e.target.result){
      // 				copyImg(e.target.result);
      // 			}
      // 		};
      // 	reader.readAsDataURL( blob );
      // };
      // var i = 0,items, item, types;
      // if( clp ){
      // 	items = clp.items;
      // 	if(!items){
      // 		return;
      // 	}
      // 	item = items[0];
      // 	types = clp.types || [];
      // 	for( ; i < types.length; i++ ){
      // 		console.log(types[i],'type');
      // 		if( types[i] === 'Files' ){
      // 			item = items[i];
      // 			break;
      // 		}
      // 	}
      // 	if( item && item.kind === 'file'){
      // 		imgReader(item);
      // 		console.log(item);
      // 	}
      // }
      // if (clp === undefined || clp === null) {
      // 	text = window.clipboardData.getData("text") || "";
      // 	if (text !== "") {
      // 		if (window.getSelection) {
      // 			var newNode = document.createElement("span");
      // 			newNode.innerHTML = text;
      // 			console.log(newNode);
      // 			window.getSelection().getRangeAt(0).insertNode(newNode);
      // 		} else {
      // 			document.selection.createRange().pasteHTML(this.toExpression(text));
      // 		}
      // 	}
      // } else {
      // 	text = clp.getData('text/plain') || "";
      // 	if (text !== "") {
      // 		document.execCommand('insertHTML', false, this.toExpression(text));
      // 	}
      // }
    },
    // 判断是否为重复的粘贴文件
    fielIsRepeat(arr, value) {
      let _this = this;
      let canvasValue = this.textMsg(this.$refs.contentInput.innerHTML);
      let imgReg = /<img.*?(?:>|\/>)/gi;
      let canvasArr = canvasValue.match(imgReg)
        ? canvasValue.match(imgReg)
        : [];
      let canvasFlag = false;
      for (let j in arr) {
        for (let i = 0; i < canvasArr.length; i++) {
          let str = canvasArr[i].substring(
            canvasArr[i].indexOf("_filepath=") + 11,
            canvasArr[i].length - 2
          );
          if (str == arr[j][`${value}`]) {
            arr.splice(j, 1);
            canvasFlag = true;
          }
        }
      }
      if (canvasFlag) _this.$Message.warning("文件重复，已过滤");
    },
    getMap() {
      let a = this.screenType ? 1 : 0;
      let res = window.external.InvokeWinFormMethod(
        "Internal.Function",
        "GetMap",
        a,
        0
      );

      console.log(res, 2720);
      // res = JSON.parse(res);
      // if (res.return_code == "TRUE") {
      //   let infs = this.$shell("GetClipboardData", []);
      //   infs = eval("(" + infs + ")");
      //   console.log(infs, 2725);
      //   if (infs.return_code === "TRUE") {
      //     if (infs.return_data.formats == "Bitmap") {
      //       // this.$refs.contentInput.focus();
      //       this.insertContent(
      //         `<img draggable="false" suffix='png' src='${infs.return_data.data}' type="img" style='max-width:8em;max-height:6em;'>`
      //       );
      //       // document.execCommand('insertHTML', false,`<img draggable="false" suffix='png' src='${infs.return_data.data}' type="img" style='max-width:8em;max-height:6em;'>`);
      //     }
      //   }
      // }
    },
    insertHtmlAtCaret(html) {
      var sel, range;
      if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
          range = sel.getRangeAt(0);
          range.deleteContents();
          var el = document.createElement("div");
          el.innerHTML = html || "";
          var frag = document.createDocumentFragment(),
            node,
            lastNode;
          while ((node = el.firstChild)) {
            lastNode = frag.appendChild(node);
          }
          range.insertNode(frag);
          if (lastNode) {
            range = range.cloneRange();
            range.setStartAfter(lastNode);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
          }
        }
      } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
      }
    },
    //@选择对象
    toSpecified(item) {
      // this.specified_show = false;
      this.$emit("changeShow", "specified_show", false); //zk修改，让父组件来修改specified_show的值
      const i = this.$refs.contentInput.innerHTML.lastIndexOf("@");
      let str = this.$refs.contentInput.innerHTML.slice(0, i + 1);
      if (item.includes("@")) {
        item = item.slice(1);
      }
      if (this.showAt) {
        //鼠标点击触发
        this.userValue = this.$refs.contentInput.innerHTML =
          str + "@" + item + "&nbsp;";
      } else {
        //键盘触发
        this.userValue = this.$refs.contentInput.innerHTML =
          str + item + "&nbsp;";
      }
      let regDel = /@((?!(@|&nbsp;)).)*&nbsp;$/g;
      this.isRegDel = regDel.test(this.$refs.contentInput.innerHTML);
      this.insertHtmlAtCaret();
      setTimeout(() => {
        this.set_last_focus(); //焦点回去
      }, 10);
    },
    //@
    specified(flag, e) {
      this.group_people = [];
      this.showAt = flag;
      if (flag) {
        console.warn(e);
        this.CoordsX = e.x;
        this.CoordsY = e.y - 30;
      }
      for (let i = 0; i < this.group_detail.users.length; i++) {
        if (this.group_detail.users[i].ID != this.myInfo.id) {
          //点击@群发去除自身
          this.group_people.push(this.group_detail.users[i].NAME);
        }
      }
      this.group_people_show = ["@所有人", ...this.group_people];
      // this.quickShow = false;
      this.$emit("changeShow", "quickShow", false); //zk修改，让父组件来修改quickShow的值
      // this.faceShow = false;
      this.$emit("changeShow", "faceShow", false); //zk修改，让父组件来修改faceshow的值
      // this.specified_show = !this.specified_show;
      this.$emit("changeShow", "specified_show"); //zk修改，让父组件来修改specified_show的值
      this.$forceUpdate();
    },
    setFaceShow() {
      // this.quickShow = false;
      this.$emit("changeShow", "quickShow", false); //zk修改，让父组件来修改quickShow的值
      // this.specified_show = false;
      this.$emit("changeShow", "specified_show", false); //zk修改，让父组件来修改specified_show的值
      // this.faceShow = !this.faceShow
      this.$emit("changeShow", "faceShow"); //zk修改，让父组件来修改faceshow的值
    },
    chooseFaceIndex(i, k) {
      this.insertContent(this.createFaceImage(i * 36 + k));
      this.$refs.contentInput.scrollTop = this.$refs.contentInput.scrollHeight;
      this.$store.state.chatInputContent[this.toInfo.id] =
        this.$refs.contentInput.innerHTML;
      // this.$refs.contentInput.innerHTML += this.createFaceImage(i * 36 + k);
      // this.userValue = this.$refs.contentInput.innerHTML;
      // this.$refs.contentInput.focus();
      // if (window.getSelection) {
      // 	let range = window.getSelection()// 创建range
      // 	range.selectAllChildren(this.$refs.contentInput)// range 选择所有子内容
      // 	range.collapseToEnd()// 光标移至最后
      // }
    },
    setFaceChoose(index) {
      this.faceChoose = index;
    },
    self_update_session(type, value, id, dura, time) {
      for (let i in this.sessionList) {
        if (this.sessionList[i].id == this.toInfo.id) {
          this.$set(this.sessionList[i], "value", value);
          this.$set(this.sessionList[i], "duration", dura);
          this.$set(this.sessionList[i], "type", type);
          this.$set(this.sessionList[i], "messageId", id);
          this.$set(this.sessionList[i], "time", time);
        }
      }
    },
    OpenFileDialog(type) {
      if (this.isDissolve) {
        this.$Message.warning("您不在该群聊中,无法操作");
        return;
      }
      if (this.personalStatus == 4) {
        this.$Message.warning("离线状态无法发送消息");
        return;
      }
      var _this = this;
      let infos = _this.$shell("OpenFileDialog_Invoke", [type]);
      console.log(infos, "files", type, "type=============");
      infos = eval("(" + infos + ")");
      if (infos.return_code == "TRUE") {
        // 判断文件大小是否超过500M，超过后无法发送
        this.$fileBigChoice(infos.return_data);
        let files = infos.return_data || [];
        let isServiceAcc = this.isService ? 1 : 0;
        let waitArr = []
        for (let i = 0; i < files.length; i++) {
          let fileInfo = files[i];
          console.log(fileInfo, "fileInfofileInfo");
          let initId = this.$func.uuid();
          let regexp = /\.(png|PNG|jpe?g|JPE?G|gif|GIF|svg|SVG|tiff)(\?.*)?$/;
          // var AllImgExt=".jpg|.jpeg|.gif|.bmp|.png|.swf|.tiff";
          // var extName = fileInfo.FileName.substring(fileInfo.FileName.lastIndexOf(".")).toLowerCase();//（把路径中的所有字母全部转换为小写）
          // if(AllImgExt.indexOf(extName+"|")==-1){
          // if(type==0){
          let maxVolume = _this.$store.state.imgMaxVolum;
          if (regexp.test(fileInfo.FileName) && fileInfo.FileSize > maxVolume) {
            _this.$Message.warning("图片太大,将以文件的形式发送.");
          }
          if (
            !regexp.test(fileInfo.FileName) ||
            fileInfo.FileSize > maxVolume
          ) {
            let table =
              _this.toInfo.isGroup == "0"
                ? _this.sqlTable.privateList
                : _this.sqlTable.messageList;
            let sdfs = _this.operationalDatabase(
              `REPLACE INTO ${table}(name,receiveId,sendId,type,value,time,messageId,isRead,isSuccessSend,isDownLoad,DownLoadId,duration,isServiceAcc,isByRead)
               VALUES('${_this.myInfo.name}','${_this.toInfo.id}','${_this.myInfo.id
              }','file','${fileInfo.FileName
              }','${new Date().getTime()}','${initId}','1','1','${fileInfo.FilePath
              }','','${fileInfo.FileSize}',${isServiceAcc},0);`
            );
            let sendValue = Object.assign(
              {
                uploading: true,
              },
              {
                upload: 1,
              },
              _this.generateMsg(
                "file",
                fileInfo.FileName,
                initId,
                fileInfo.FileSize,
                0,
                "",
                fileInfo.path || fileInfo.FilePath
              )
            ); //新增文件路径参数
            console.log("===================");
            console.log(fileInfo.FileName, initId, fileInfo);
            this.$emit("updateFile", sendValue);
            this.$emit("updateChatList", sendValue);
            // _this.chatList[0].unshift(sendValue);
            this.self_update_session(
              "file",
              "[文件]",
              initId,
              fileInfo.FileSize,
              new Date().getTime()
            );
            console.log(
              "1",
              _this.toInfo.id,
              initId,
              fileInfo.FilePath,
              "文件上传信息"
            );
            let infos = _this.$shell("UpLoadFile", [
              "1",
              _this.toInfo.id,
              initId,
              fileInfo.FilePath,
              parseInt(_this.toInfo.isGroup),
              _this.toInfo.name,
              _this.myInfo.id,
            ]);
            console.log(infos, "文件上传接口返回");
            try {
              infos = JSON.parse(infos);
              if (infos.return_code != "TRUE") {
                _this.$Message.warning(infos.return_msg);
              }
            } catch (err) {
              _this.$Message.warning("上传文件出错,请稍后再试");
            }
          } else {
            let sendValue = Object.assign(
              {
                uploading: true,
              },
              {
                upload: 1,
              },
              _this.generateMsg(
                "image",
                fileInfo.FileName,
                initId,
                fileInfo.FileSize,
                0
              )
            );
            this.$emit("updateFile", sendValue);
            waitArr.push({
              messageId: initId,
              fileInfo: fileInfo,
              fileId: '',
            })
            let infos = _this.$shell("UpLoadFile", [
              "0",
              _this.toInfo.id,
              initId,
              fileInfo.FilePath,
              parseInt(_this.toInfo.isGroup),
              _this.toInfo.name,
              _this.myInfo.id,
            ]);
            try {
              infos = JSON.parse(infos);
              if (infos.return_code != "TRUE") {
                _this.$Message.warning(infos.return_msg);
              }
            } catch (err) {
              _this.$Message.warning("发送图片出错,请稍后再试");
            }
          }
        }
        _this.$Message.loading({
          content: "发送中，请等待",
          duration: 10
        });
        this.$store.commit('setChatChooseFileWait',{
          waitArr: waitArr,
          type: 'wait',
          myInfoId: _this.myInfo.id,
          toInfoId: _this.toInfo.id,
        })
      } else {
        _this.$Message.warning(infos.return_msg);
      }
    },
    uploadImgErr(table, initid, base) {
      console.log(3193);
      // 查询当前消息状态是否为1
      let msgType = JSON.parse(
        this.$shellSQL(
          JSON.stringify({
            Sqlstr: `SELECT isSuccessSend FROM ${table} WHERE messageId = '${initid}'`,
          }),
          1
        )
      );
      if (msgType.list[0].isSuccessSend == 1) {
        JSON.parse(
          this.$shellSQL(
            JSON.stringify({
              Sqlstr: `UPDATE ${table}
                SET isSuccessSend = '2',
                rawValue = '${base}'
                WHERE
                  messageId = '${initid}'`,
            })
          )
        );
        this.$store.commit("setOvertimeMsgKey", initid);
      }
    },
    getSelectionCoords(win) {
      //获取当前光标的坐标
      win = win || window;
      var doc = win.document;
      var sel = doc.selection,
        range,
        rects,
        rect;
      var x = 0,
        y = 0;
      if (sel) {
        if (sel.type != "Control") {
          range = sel.createRange();
          range.collapse(true);
          x = range.boundingLeft;
          y = range.boundingTop;
        }
      } else if (win.getSelection) {
        sel = win.getSelection();
        if (sel.rangeCount) {
          range = sel.getRangeAt(0).cloneRange();
          if (range.getClientRects) {
            range.collapse(true);
            rects = range.getClientRects();
            if (rects.length > 0) {
              rect = rects[0];
            }
            // 光标在行首时，rect为undefined
            if (rect) {
              x = rect.left;
              y = rect.top;
            }
          }
          // Fall back to inserting a temporary element
          if ((x == 0 && y == 0) || rect === undefined) {
            var span = doc.createElement("span");
            if (span.getClientRects) {
              // Ensure span has dimensions and position by
              // adding a zero-width space character
              span.appendChild(doc.createTextNode("\u200b"));
              range.insertNode(span);
              rect = span.getClientRects()[0];
              x = rect.left;
              y = rect.top;
              var spanParent = span.parentNode;
              spanParent.removeChild(span);

              // Glue any broken text nodes back together
              spanParent.normalize();
            }
          }
        }
      }
      this.CoordsX = x;
      this.CoordsY = window.innerHeight - y;
    },
  },
  created() {
    window.getDropChangeData = this.getDropChangeData;
    this.screenType = this.$store.state.screenshotFilter;
  },
  mounted() {
    if(this.$store.state.toReply){
      this.isReplay = true
    }
    const that = this;
    document.onkeydown = function (e) {
      if (!that.contentFocus) return;
      var keyCode = e.keyCode || e.which || e.charCode;
      var ctrlKey = e.ctrlKey || e.metaKey;
      if (ctrlKey && keyCode == 67) {
        //Ctrl+c复制事件
        that.copyText = that.getSelectionContainerElem();
        that.copyValue();
        e.preventDefault();
      } else if (ctrlKey && keyCode == 88) {
        //Ctrl+x剪切事件
        that.copyText = that.getSelectionContainerElem();
        setTimeout(() => {
          that.copyValue();
        }, 10);
      }
    };
    this.$nextTick(() => {
      // 设置最后光标对象
      this.$refs.contentInput.focus();
      var selection = getSelection();
      if (selection) {
        this.lastEditRange = selection.getRangeAt(0);
      }
      // console.log(this.lastEditRange,'光标')
      // 以下功能可用,已废弃 改由外壳返回拖拽数据
      document.ondragleave = (e) => {
        // this.$refs.contentInput.style.border='2px solid #fff';
        e.preventDefault(); //阻止离开时的浏览器默认行为
      };
      document.ondrop = (e) => {
        e.preventDefault();
      };
      document.ondragenter = (e) => {
        // console.log(e.target.getAttribute('name'))
        this.$refs.contentInput.focus();
        // this.$refs.contentInput.style.border= '2px dashed #1879bf';
        e.preventDefault(); //阻止拖入时的浏览器默认行为
      };
      document.ondragover = (e) => {
        // this.$refs.contentInput.style.border= '2px dashed #1879bf';
        e.preventDefault(); //阻止拖来拖去的浏览器默认行为
      };

      let value = this.$store.state.font_configure;
      if (value != null) {
        let temp = JSON.parse(value);
        this.sizeValue = temp.size;
        this.colorValue = temp.color;
        this.boldValue = temp.bold;
      }
    });
  },
};
</script>
<style lang="less" scoped>
.replayWrap {
  display: flex;
  align-items: center;
  position: fixed;
  bottom: 20px;
  left: 346px;

  #replay {
    background: #e8e8e8;
    border: 1px solid #e8e8e8;
    border-radius: 3px;
    max-width: 280px;
    margin-right: 10px;
    padding: 3px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;

  }

  img {
    width: 16px;
    height: 16px;
  }
}
</style>
